Showing posts with label GET. Show all posts
Showing posts with label GET. Show all posts

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

        }







Sunday, December 27, 2015

Bind data from XML using Angularjs

Angularjs - XML Bind data - bind first element from xml file.


Hello It's easy to bind data from JSON in html using Angularjs. but now a days people are not using XML  file for communicate between client and server.

We have one API service which will return XML object.


Above API return word of the day 

HTML Will like below 


<html>
   <head id="Head1" runat="server">
      <title></title>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
      <script type="text/javascript">
         var myApp = angular.module('myApp', []);
         
         myApp.controller('myController', function ($scope, $http) {
         
         
         
             $http.get("http://api.wordnik.com/v4/words.xml/wordOfTheDay?api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5").success(function (xml) {
         
                 $scope.word = $(xml).find('word').text();
                 $scope.defination = $(xml).find('definition text').text();
                 $scope.example = $(xml).find('example text:first').text();
                 $scope.date = $(xml).find('publishDate').text();
         
             }).error(function (status) {
                 alert(status);
         
             });
         
     
         
         
         
         
         
         });
         
         
      </script>
   </head>
   <body>
      <div ng-app="myApp" ng-controller="myController">
         Word : <b>{{word}} </b><b>{{date | date:'MM/dd/yyyy'}}</b>
         <br />
         Defination <b>{{defination}}</b>
         <br />
         Example : <b>{{example}}</b>
         <br />
         Example : <b>{{example2}}</b>
         <h3></h3>
       
      </div>
   </body>
</html>

Featured Post