In C#, What Is The Method To Invoke REST API Calls?

To make calls to a REST API using C#, you can use the HttpClient class from the System.Net.Http namespace. Here is an example of how you can make GET and POST requests to a REST API using C#:

  1. First, make sure to import the required namespaces:
using System;
using System.Net.Http;
using System.Threading.Tasks;
  1. To make a GET request, use the HttpClient’s GetAsync method:
public async Task<string> GetAsync(string url)
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();

        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }
}
  1. To make a POST request, use the HttpClient’s PostAsync method:
public async Task<string> PostAsync(string url, string json)
{
    using (HttpClient client = new HttpClient())
    {
        HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }
}

In both cases, url represents the endpoint of the REST API, and json is the JSON data you want to send (in case of POST request).

Note that the above examples are asynchronous methods. You can call them from an asynchronous method using the await keyword.

Here’s an example of how you can use these methods:

string apiUrl = "https://api.example.com/data";
string jsonResponse = await GetAsync(apiUrl);
Console.WriteLine(jsonResponse);

string postData = "{\"name\":\"John\",\"age\":30}";
string postResponse = await PostAsync(apiUrl, postData);
Console.WriteLine(postResponse);

Make sure to replace the apiUrl with the actual API endpoint and adjust the JSON data as required for your specific API.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!