Using HttpClient to access API resources

Oftentimes we will have the need to call into an API to load resources. HttpClient class provides in the System.Net namespace provides all the required functionality to interact with an API in the usual ways.

In the example below, we have a C# POCO called CustomerRequest which is used to encapsulate the data to be sent to the API. The API does some processing behind the scenes and then returns some Json using the HttpResponseMessage's Content property. The returned Json is deserialized into a CustomerResponse object ready for use by the calling method.

using (var client = new HttpClient())
{
var serializedBody = JsonConvert.SerializeObject(customerRequest);
var url = string.Format("{0}/{1}", ConfigurationManager.AppSettings["API_URL"], "customer");
var response = await client.PostAsync(url, new StringContent(serializedBody, Encoding.UTF8, "application/json"));
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<CustomerResponse>(content);
}
view raw gistfile1.cs hosted with ❤ by GitHub

Note the use of NewtonSoft's popular Json.NET library to perform the serialization and deserialization of our classes.

Popular posts from this blog

A Simple 3 Layer Architecture