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

How to consume a Rest API as clients with C#

  • 4 min

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 that we have to interact with them from our application.

Fortunately, communicating with a REST API from a .Net application is easy with the HttpWebRequest class, included by default.

For this post, we will use our sample REST API in NodeJS that we saw in this post, and we have frequently used on the blog as the basis for a “well” structured REST API.

To consume our sample 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 REST API test, 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);
}
Copied!

Now, the definition of these functions could be as follows.

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
  }
}
Copied!

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 can see, the code, while not particularly difficult, is somewhat cumbersome and repetitive. In the next post, we will see how to consume a REST API more easily thanks to the RestSharp library.