Introduction
This following blog provides code snippetS to consume API in c# hosted in your local machine using HttpClient class.
Getting Started
Let's say a Restful Web API has been build which exposes the 'GetStudentDetails' function, hosted in your local machine with port number 9002 and the API support JSON request and response format.
you won't call API from C# application. It is very simple to consume and the process of consuming Restful Web API is the same as consuming web service.
The following blog shares code snippet that conumes Restful Web API, it is developed in console application and can be used with any other application like MVC, WPF, Winform etc which supports C# language.
Web API Response Content Details
//Response class
public class StudentResponse<T>
{
public int Code { get; set; }
public string Message { get; set; }
public List<T> Result { get; set; }
}
//Student Details class
public class StudentDetails
{
public int ID { get; set; }
public int Name { get; set; }
}
The above details are the response content of Web API which we are going to handle, the below details are the codes for requesting Web API and handling his response.Code Snippet For Consuming Restful Web API
class Program
{
static async Task<StudentResponse<StudentDetails>> GetProductAsync()
{
StudentResponse<StudentDetails> studentresponse = new StudentResponse<StudentDetails>();
List<StudentDetails> students = new List<StudentDetails>();
try
{
// Posting.
using (var client = new HttpClient())
{
// Assign API address.
client.BaseAddress = new Uri("http://localhost:9002/");
// Setting content type in header for request format(Content type).
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Setting timeout.
client.Timeout = TimeSpan.FromSeconds(Convert.ToDouble(1000000));
// Initialization.
HttpResponseMessage response = new HttpResponseMessage();
// Requesting to GetStudentDetails method of API
response = await client.GetAsync("/GetStudentDetails");
// Handling response
if (response.IsSuccessStatusCode)
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
//Converting response to student list
students = JsonConvert.DeserializeObject<List<StudentDetails>>(result);
studentresponse.Result = students;
studentresponse.Message = "Success";
// Releasing response.
response.Dispose();
}
else
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
studentresponse.Message = result;
studentresponse.Code = 403;
}
}
}
catch (Exception ex)
{
throw ex;
}
return studentresponse;
}
}
}
The above code example request to the Rest Web API 'GetStudentDetails' function which returns list of student details. The required namespaces of the above code are Newtonsoft.Json and System.Net.Http.Headers, the DLL for Newtonsoft.Json namespace you can download from Nueget.Consumeing Restful Web API Steps
The flowing below details describes the step by step process of consuming Restful Web API.- First initialize the object of HttpClient.
- Then sets base address of Restful Web API.
- Set the request format of header for example, if Web API exposes result in xml format then set it as 'application/xml' or for json then set 'application/json'.
- Create objec of HttpResponseMessage class for handling response from web api.
- Call any function of HttpClient object like if you want to call get mentohd of Web API then call GetAsync.
- Check the result of of response, based on the response read the result.
Related Articles
- Difference Between DataContractSerializer and XMLSerializer
- Getting Client's IP Address in WCF Service
- Consuming Restful API with Bearer Token Authentication using HttpWebRequest
- Concurrency Mode In WCF
- Difference between WCF And Web Service
Thanks