consume rest api in csharp

In C#, we can use the HttpClient class to consume REST APIs. To get started, we need to create an instance of the HttpClient class and use its GetAsync() method to make a GET request to the API endpoint. Here's an example:

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

public class Program
{
    public static async Task Main(string[] args)
    {
        using var client = new HttpClient();

        var response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts");
        var content = await response.Content.ReadAsStringAsync();

        Console.WriteLine(content);
    }
}
395 chars
17 lines

In the example above, we first create an instance of the HttpClient class. We then use the GetAsync() method to make a GET request to the URL https://jsonplaceholder.typicode.com/posts. The response from the API is stored in the response variable. We then read the content of the response using the ReadAsStringAsync() method and store it in the content variable. Finally, we print the content of the response to the console.

Note that we're using the await keyword to asynchronously wait for the response from the API. This helps to ensure that our program doesn't block while waiting for the API to respond.

related categories

gistlibby LogSnag