HomeAbout Me

Generic wrapper to consume RESTful API in C#

By Sri Gunnala
Published in Microsoft .NET
August 30, 2019
1 min read
Generic wrapper to consume RESTful API in C#

If the need is to make REST API calls frequently in a C# .NET project, I would prefer having a generic wrapper method around the HttpClient object(whatever other clients you prefer). This is to eliminate duplicate code and you can easily deal with REST API exceptions. This generic wrapper also supports translating your JSON data into a class object of a given type. There are some third-party DLLs out there that you can use straight away, but I would prefer doing it on my own as it is on small scale and you can have better control over it. Here is the generic wrapper to consume ASP.NET Web API calls in any C# .NET project.

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;

    /// <summary>
    /// A generic wrapper class to REST API calls
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class HTTPClientWrapper<T> where T : class
    {
        /// <summary>
        /// For getting the resources from a web api
        /// </summary>
        /// <param name="url">API Url</param>
        /// <returns>A Task with result object of type T</returns>
        public static async Task<T> Get(string url)
        {
            T result = null;
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync(new Uri(url)).Result;

                response.EnsureSuccessStatusCode();
                await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
                {
                    if (x.IsFaulted)
                        throw x.Exception;

                    result = JsonConvert.DeserializeObject<T>   (x.Result);
                });
            }

            return result;
        }

        /// <summary>
        /// For creating a new item over a web api using POST
        /// </summary>
        /// <param name="apiUrl">API Url</param>
        /// <param name="postObject">The object to be created</param>
        /// <returns>A Task with created item</returns>
        public static async Task<T> PostRequest(string apiUrl, T postObject)
        {
            T result = null;

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(apiUrl, postObject, new JsonMediaTypeFormatter()).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
                {
                    if (x.IsFaulted)
                        throw x.Exception;

                    result = JsonConvert.DeserializeObject<T>(x.Result);

                });
            }

            return result;
        }

        /// <summary>
        /// For updating an existing item over a web API using PUT
        /// </summary>
        /// <param name="apiUrl">API Url</param>
        /// <param name="putObject">The object to be edited</param>
        public static async Task PutRequest(string apiUrl, T putObject)
        {
            using (var client = new HttpClient())
            {
                var response = await client.PutAsync(apiUrl, putObject, new JsonMediaTypeFormatter()).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
            }
        }
    }

Tags

#dotnetcore
Previous Article
Use Font Awesome Angular Component in 5 simple steps
Sri Gunnala

Sri Gunnala

Learner | Reader | Blogger | Azure Enthusiast

Topics

Front End
Microsoft Azure
Microsoft .NET

Newsletter

Sri Gunnala - Make sure to subscribe to newsletter and be the first to know the news.

Related Posts

.NET Core Worker Service as Windows Service or Linux Daemons
September 20, 2019
2 min

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use

Social Media