Language: EN

como-consumir-un-api-rest-como-clientes-con-c

How to consume a Rest API as clients with C#

Today we are going to see how to consume a Rest API from an application written in .Net Framework, without the need for third-party libraries.

As we know, providing a Rest API is a common way of communicating with web applications. Therefore, it is common for us to have to interact with them from our application.

Fortunately, communicating with a Rest API from an application in .Net is simple with the HttpWebRequest class, included by default.

For this post we will use our example Rest API in NodeJS that we saw in this post, and we have frequently used in the blog as the basis of a “well” structured Rest API.

To consume our example Rest API from .Net we are going to create a sample application. A console application, for example, will be sufficient.

Inside we replace the main method with our test of the Rest API, with the functions that test the different functionalities.

static void Main(string[] args)
{
  GetItem(10);
  GetItems();
  GetItems("ABC");
  PostItem("NewItem");
  PutItem(4, "ReplaceItem");
  DeleteItem(5);
}

Now, the definition of these functions could be the following.

private static void GetItem(int id)
{
  var url = $"http://localhost:8080/item/{id}";
  var request = (HttpWebRequest)WebRequest.Create(url);
  request.Method = "GET";
  request.ContentType = "application/json";
  request.Accept = "application/json";

  try
  {
    using (WebResponse response = request.GetResponse())
    {
      using (Stream strReader = response.GetResponseStream())
      {
        if (strReader == null) return;
        using (StreamReader objReader = new StreamReader(strReader))
        {
          string responseBody = objReader.ReadToEnd();
          // Do something with responseBody
          Console.WriteLine(responseBody);
        }
      }
    }
  }
  catch (WebException ex)
  {
    // Handle error
  }
}

private static void GetItems()
{
  var url = $"http://localhost:8080/items";
  var request = (HttpWebRequest)WebRequest.Create(url);
  request.Method = "GET";
  request.ContentType = "application/json";
  request.Accept = "application/json";

  try
  {
    using (WebResponse response = request.GetResponse())
    {
      using (Stream strReader = response.GetResponseStream())
      {
        if (strReader == null) return;
        using (StreamReader objReader = new StreamReader(strReader))
        {
          string responseBody = objReader.ReadToEnd();
          // Do something with responseBody
          Console.WriteLine(responseBody);
        }
      }
    }
  }
  catch (WebException ex)
  {
    // Handle error
  }
}

private static void GetItems(string filter)
{
  var url = $"http://localhost:8080/items?filter={filter}";
  var request = (HttpWebRequest)WebRequest.Create(url);
  request.Method = "GET";
  request.ContentType = "application/json";
  request.Accept = "application/json";

  try
  {
    using (WebResponse response = request.GetResponse())
    {
      using (Stream strReader = response.GetResponseStream())
      {
        if (strReader == null) return;
        using (StreamReader objReader = new StreamReader(strReader))
        {
          string responseBody = objReader.ReadToEnd();
          // Do something with responseBody
          Console.WriteLine(responseBody);
        }
      }
    }
  }
  catch (WebException ex)
  {
    // Handle error
  }
}

private static void PostItem(string data)
{
  var url = $"http://localhost:8080/items";
  var request = (HttpWebRequest)WebRequest.Create(url);
  string json = $"{{\"data\":\"{data}\"}}";
  request.Method = "POST";
  request.ContentType = "application/json";
  request.Accept = "application/json";

  using (var streamWriter = new StreamWriter(request.GetRequestStream()))
  {
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
  }

  try
  {
    using (WebResponse response = request.GetResponse())
    {
      using (Stream strReader = response.GetResponseStream())
      {
        if (strReader == null) return;
        using (StreamReader objReader = new StreamReader(strReader))
        {
          string responseBody = objReader.ReadToEnd();
          // Do something with responseBody
          Console.WriteLine(responseBody);
        }
      }
    }
  }
  catch (WebException ex)
  {
    // Handle error
  }
}

private static void PutItem(int id, string data)
{
  var url = $"http://localhost:8080/items";
  var request = (HttpWebRequest)WebRequest.Create(url);
  string json = $"{{\"id\":\"{id}\",\"data\":\"{data}\"}}";
  request.Method = "PUT";
  request.ContentType = "application/json";
  request.Accept = "application/json";

  using (var streamWriter = new StreamWriter(request.GetRequestStream()))
  {
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
  }

  try
  {
    using (WebResponse response = request.GetResponse())
    {
      using (Stream strReader = response.GetResponseStream())
      {
        if (strReader == null) return;
        using (StreamReader objReader = new StreamReader(strReader))
        {
          string responseBody = objReader.ReadToEnd();
          // Do something with responseBody
          Console.WriteLine(responseBody);
        }
      }
    }
  }
  catch (WebException ex)
  {
    // Handle error
  }
}

private static void DeleteItem(int id)
{
  var url = $"http://localhost:8080/items/{id}";
  var request = (HttpWebRequest)WebRequest.Create(url);
  request.Method = "DELETE";
  request.ContentType = "application/json";
  request.Accept = "application/json";

  try
  {
    using (WebResponse response = request.GetResponse())
    {
      using (Stream strReader = response.GetResponseStream())
      {
        if (strReader == null) return;
        using (StreamReader objReader = new StreamReader(strReader))
        {
          string responseBody = objReader.ReadToEnd();
          // Do something with responseBody
          Console.WriteLine(responseBody);
        }
      }
    }
  }
  catch (WebException ex)
  {
    // Handle error
  }
}

esp8266-client-api-rest-nodejs

Of course, if we run this simple example we will see that we correctly receive the calls from our simulated Rest API.

As we see the code, without being particularly difficult, is somewhat cumbersome and repetitive. In the next entry, we will see how to consume a Rest API in a simpler way thanks to the RestSharp library.