Some My Experiences

Header Ads

Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Sunday 28 October 2018

Calling API Using HttpClient in C#

This section show example how to calling API using HttpClient in C#.

ApiCallerHelper.cs
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;

namespace WebApplicationMvcApi.Helper
{
    public class ApiCallerHelper
    {
        private static string endpointName = "endpoint";
        public static HttpResponseMessage getResult(HttpRequestMessage request)
        {

            var queryStringNvp = request.GetQueryNameValuePairs();
            var endpoint = getEndpoint(queryStringNvp);
            var requestParam = getRequestParams(queryStringNvp);
            var actualEndpointWithParam = concatUrlWithParam(endpoint, requestParam);
            
            var headers = request.Headers;

            var newRequest = new HttpRequestMessage(request.Method, actualEndpointWithParam);
            if(request.Method != HttpMethod.Get && request.Method != HttpMethod.Delete)
            {
                newRequest.Content = request.Content;
            }

            var ignoreClientHeaders = new List<string> { "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Host", "Connection", "Cache-Control", "Origin" };
            
            var headersEnumerable = (IEnumerable<KeyValuePair<string, IEnumerable<string>>>)headers;
            foreach (var header in headersEnumerable)
            {
                if(!ignoreClientHeaders.Exists(item => item.ToLower().Equals(header.Key.ToLower())))
                    newRequest.Headers.Add(header.Key, header.Value);
            }

            return doRequest(newRequest);
        }
        
        private static string concatUrlWithParam(string url, string queryString)
        {
            return string.IsNullOrEmpty(queryString) ? url : string.Format("{0}?{1}", url, queryString);
        }

        private static string getRequestParams(IEnumerable<KeyValuePair<string, string>> nameValuePairs)
        {
            var requestParams = nameValuePairs.Where(item => !item.Key.ToLower().Equals(endpointName.ToLower()))
                .Select(item => string.Format("{0}={1}", item.Key, item.Value));
            return string.Join("&", requestParams); ;
        }

        private static string getEndpoint(IEnumerable<KeyValuePair<string, string>> nameValuePairs)
        {
            var endpointKvp = nameValuePairs.FirstOrDefault(item => item.Key.ToLower().Equals(endpointName.ToLower()));
            if(!endpointKvp.Equals(default(KeyValuePair<string, string>)))
            {
                return endpointKvp.Value;
            }
            return null;
        }

        public static HttpResponseMessage doRequest(HttpRequestMessage request)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                return client.SendAsync(request).Result;
            }
        }
    }
        
}

API Caller Usage
[RoutePrefix("api/caller")]
public class CallerController : ApiController
{
    [Route("do")]
    [HttpGet, HttpPost, HttpPut, HttpPatch, HttpDelete]
    public HttpResponseMessage Do()
    {
        return ApiCallerHelper.getResult(Request);
    }
}

Example: POST Request
POST /api/caller/do?endpoint=https://reqres.in/api/register HTTP/1.1
Host: localhost:57596
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 58b8c84f-89a5-ec5d-5196-17f2814cabee

{
    "email": "alex@son.com",
    "password": "Lex_One"
}

POST Response
{
    "token": "QpwL5tke4Pnpja7X"
}

Environment
Windows 10 Home 64bit
Visual Studio 2017 (Version 15.8.4)
Target .Net Framework 4.5.2

Thursday 17 March 2016

How To Use MailChimp API V3.0 in C#

 To use MailChimp API V3.0 in C# language, do the steps below:
  1. Create C# Web Form Project called 'MailChimpV3'.
  2. Add Json.NET Framework to project Reference. Here I use  Json 8.0.2 version from Newtonsoft.
  3. Create folder called `MailChimp` on the project.
  4. Add C# class called `MailChimpManager.cs` in the `MailChimp` folder, location would be like `\MailChimpV3\MailChimp\MailChimpManager.cs`. Then copy the code below.