Consuming RESTFUL Web API


Introduction

This following blog provides code snippet to consume restful web API hosted in your local machine using HttpClient class.

Getting Started

Let's say a Restful Web API has been build which exposes 'GetStudentDetails' function, hosted in your local machine with port number 9002 and the API support JSON request and response format.

you want comusme that API in your application. It is very simple to consume and the process of consuming Restful Web API is same like 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; }  
   }  
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.
  1. First initialize the object of HttpClient.
  2. Then sets base address of Restful Web API.
  3. 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'.
  4. Create objec of HttpResponseMessage class for handling response from web api.
  5. Call any function of HttpClient object like if you want to call get mentohd of Web API then call GetAsync.
  6. Check the result of of response, based on the response read the result.

Thanks
Kailash Chandra Behera


No comments:

Post a Comment