call api in csharp

To call an API in C#, you can use the HttpClient class in the System.Net.Http namespace. Here's an example code snippet that demonstrates how to perform a GET request and handle the response:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

public async Task<string> CallApi(string url) 
{
    // create a new HttpClient instance
    using (var client = new HttpClient())
    {
        // send a GET request to the specified URL
        HttpResponseMessage response = await client.GetAsync(url);

        // throw an exception if the request was not successful
        response.EnsureSuccessStatusCode();

        // read the response content as a string
        string responseBody = await response.Content.ReadAsStringAsync();

        return responseBody;
    }
}
594 chars
22 lines

To perform other HTTP methods (e.g. POST, PUT, DELETE), simply change the method on the HttpClient instance (e.g. client.PostAsync).

You may also need to handle different types of response data. If the API returns JSON, you can use a library like Newtonsoft.Json to deserialize the response content into a C# object:

main.cs
using Newtonsoft.Json;

public async Task<TResponse> CallApi<TResponse>(string url) 
{
    // create a new HttpClient instance
    using (var client = new HttpClient())
    {
        // send a GET request to the specified URL
        HttpResponseMessage response = await client.GetAsync(url);

        // throw an exception if the request was not successful
        response.EnsureSuccessStatusCode();

        // read the response content as a string
        string responseBody = await response.Content.ReadAsStringAsync();

        // deserialize the JSON response into a C# object
        TResponse responseData = JsonConvert.DeserializeObject<TResponse>(responseBody);

        return responseData;
    }
}
712 chars
23 lines

related categories

gistlibby LogSnag