Sunday, November 12, 2017

Calling / Consume a Web API using HttpClient in c# with Example

Calling / Consume a Web API using HttpClient in c# 

Step 1 :  Open Visual Studio  Add new Console application.

We will create a client Application which will consume GET & POST method.





Step 2 :   Add Reference System.Net.Http.HttpClient.  for  use HttpClient 


We are using HttpClient to  sending and receive Http request -responses. we need to add below two reference in console application for call Web Api  using HttpClient .

System.Net,Http;              
System.Web.Exension;     // used for Deserialize   

Step 3 :  Create a helper class 

We will create a method for consume GET & POST  API using c#.  we are using generic types for maximize code reuse, type safety and performance.  




#region Helper Class
    public class clsHelper
    {

        public ClsAPIResponse CallAPI<U, P, T>(U url, P param, T type)
        {

            HttpClient client = new HttpClient();
            ClsAPIResponse objresponse = new ClsAPIResponse();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            dynamic response;
            if (type.ToString() == MethodTypes.POST.ToString())
            {
                response = client.PostAsync(url.ToString(), new StringContent(new JavaScriptSerializer().Serialize(param), Encoding.UTF8, "application/json")).Result;
            }
            else if (type.ToString() == MethodTypes.GET.ToString())
            {
                response = client.GetAsync(url.ToString()).Result;

            }
            else
            {
                response = client.PostAsync(url.ToString(), new StringContent(new JavaScriptSerializer().Serialize(param), Encoding.UTF8, "application/json")).Result;
            }


            var contents = response.Content.ReadAsStringAsync();

            // Bind Response. 

            objresponse.StatusCode = (int)response.StatusCode;
            objresponse.Message = response.ReasonPhrase.ToString();
            objresponse.ResponseString = contents.Result.ToString().TrimStart('\"').TrimEnd('\"').Replace("\\", "");



            return objresponse;
        }

        public enum MethodTypes { GET, POST, PUT, DELETE };

        public class ClsAPIResponse
        {
            public int StatusCode { get; set; }

            public string Message { get; set; }

            public string ResponseString { get; set; }


        }
    }
    #endregion





Step 4 :  Create a classes for GET & Post




#region Classes For Post Method
    public class clsInput
    {
        public string name { get; set; }
        public string job { get; set; }
    }

    public class clsPostResponse
    {
        public string name { get; set; }
        public string job { get; set; }
        public string id { get; set; }
        public DateTime createdAt { get; set; }
    }

    #endregion

    #region Classes For Get Method
    public class clsGetResponseData
    {
        public int id { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string avatar { get; set; }
    }

    public class clsGetResponse
    {
        public clsGetResponseData data { get; set; }
    }
    #endregion




Step 5 :  Call GET & POST Method Using HttpClient.

we are using "reqres.in" API for demo purpose.  




static void Main(string[] args)
        {

            clsHelper obj = new clsHelper();

            #region PostMethod
            // 1. For Post Method Call 

            clsHelper.ClsAPIResponse objPostResponse = new clsHelper.ClsAPIResponse();

            // Input 
            clsInput objinput = new clsInput();
            objinput.job = "morpheus";
            objinput.name = "leader";

            // Call Method 
            objPostResponse = obj.CallAPI<string, clsInput, clsHelper.MethodTypes>("https://reqres.in/api/users", objinput, clsHelper.MethodTypes.POST);
            clsPostResponse objPostResult = JsonConvert.DeserializeObject<clsPostResponse>(objPostResponse.ResponseString);
            #endregion

            #region GetMethod
            clsHelper.ClsAPIResponse objGetResponse = new clsHelper.ClsAPIResponse();
            objGetResponse = obj.CallAPI<string, clsInput, clsHelper.MethodTypes>("https://reqres.in/api/users/2", objinput, clsHelper.MethodTypes.GET);

            clsGetResponse objGetResult = JsonConvert.DeserializeObject<clsGetResponse>(objGetResponse.ResponseString);
            #endregion

        }







No comments:

Post a Comment

Featured Post