DEV Community

Nwanguma Victor
Nwanguma Victor

Posted on

5 3

ReUsable UseFetch Utility in C#

This ReUsable UseFetch Utility used for API data fetching, it can serialize and deserialize objects on the fly.

Headers

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
Enter fullscreen mode Exit fullscreen mode

Class

public static class UseFetch
    {
        public static TResponse Get<TResponse>(string url,
            Dictionary<string, string> headers = null)
            where TResponse : class
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                var response = client.GetAsync(url).Result;

                var responseString = response.Content.ReadAsStringAsync().Result;

                var deserializedResponse = JsonConvert.DeserializeObject<TResponse>(responseString);

                return deserializedResponse;
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }

        public static TResponse Post<TResponse, TRequest>(string url, TRequest request,
            Dictionary<string, string> headers = null)
            where TRequest : class, new()
            where TResponse : class
        {
            try
            {
                var serializeRequest = JsonConvert.SerializeObject(request);

                var content = new StringContent(serializeRequest);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                var response = client.PostAsync(url, content).Result;

                var responseString = response.Content.ReadAsStringAsync().Result;

                var deserializedResponse = JsonConvert.DeserializeObject<TResponse>(responseString);

                return deserializedResponse;
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

enjoy šŸš€

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
kanebarton profile image
Kane Barton ā€¢

Iā€™d suggest avoiding a custom developed utility class like this as there are some common pitfalls (e.g., HttpClient should be static, correctly using async/await, no transient retries, memory over allocations not using strings) but instead use a more standard library like: System.Net.Http.Json

docs.microsoft.com/en-us/dotnet/ap....

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay