REST API Calls with HttpClient in C#



In modern applications, it is often necessary to communicate with a web server to fetch the data, create data, or interact with other online systems. To create this type of applications that communicate with a web server or backend server, we use the REST API (Representational State Transfer APIs). Basically, REST APIs use HTTP methods such as GET, POST, PUT, and DELETE to perform CRUD operations (Create, Read, Update, Delete). Read this chapter to learn how to write and use "REST API" calls using the "HttpClient" class.

What is HttpClient?

In C#, HttpClient is the class that uses the system.Net.Http namespace that allows your application to sent Http Request and receive HTTP response from web server. It supports both synchronous and asynchronous communication, enabling non-blocking API calls that keep your application responsive.

Why Use HttpClient?

HttpClient is useful for the following reasons −

  • Simple − Easy to send the HTTP request with minimal code.
  • Asynchronous Support − It uses the async/await for non-blocking I/O.
  • CRUD Operation − Support All HTTP verbs(GET, POST, PUT, DELETE).
  • Data Format − It handle easily JSON and XML Data.
  • Reusability − It can be reused for the multiple request, improving performance.

Rest API Operations

Following are the important operations of a REST API; let's understand them and their work −

  • GET − Used to Fetch the data from the server.
  • POST − Used to create the data into the server.
  • PUT − Used to update the existing data.
  • DELETE − Used to delete the existing data.

Creating a REST API Test Application

So far you have understood what HttpClient and REST API are; now it's time to demonstrate how HttpClient works by creating a C# console application.

First of all, open Visual Studio Code and create the project using this command: "dotnet new console -n MyConsoleApp". Then install this package, "Install-Package Newtonsoft.Json"; it allows JSON serialization and deserialization.

Folder Structure

The folder structure looks like this −

rest_api_calls

File − "Post.cs" This file define the your model class, representing a single post object returned by the API.

namespace RestApiWithHttpClient {
   public class Post {
      public int Id { get; set; }
      public int UserId { get; set; }
      public string Title { get; set; }
      public string Body { get; set; }
   }
}

File: Program.cs

In this file, we will be implementing the full logic needed to perform CRUD operations using HttpClient.

// C# - REST API CRUD Example using HttpClient
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace RestApiWithHttpClient {
   class Program {
      // Create one HttpClient object for the entire application
      static readonly HttpClient client = new HttpClient();

      static async Task Main(string[] args) {
         client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");

         Console.WriteLine("** Testing REST API Calls with HttpClient **\n");

         await GetAllPostsAsync();
         await CreatePostAsync();
         await UpdatePostAsync();
         await DeletePostAsync();

         Console.WriteLine("\n** All operations completed successfully! **");
      }

      // GET: Fetch all posts
      static async Task GetAllPostsAsync() {
         Console.WriteLine("GET: Fetching posts...");

         HttpResponseMessage response = await client.GetAsync("posts");

         if (response.IsSuccessStatusCode) {
            string data = await response.Content.ReadAsStringAsync();

            // print part of response
            Console.WriteLine("\nGET Response:\n" + data.Substring(0, 200) + "...\n");
         } else {
            Console.WriteLine($"GET failed: {response.StatusCode}");
         }
      }

      //  POST: Create a new post 
      static async Task CreatePostAsync() {
         Console.WriteLine("POST: Creating a new post...");

         var newPost = new Post {
            UserId = 1,
            Title = "Testing HttpClient POST",
            Body = "This is a dummy post created using HttpClient."
         };

         var json = JsonConvert.SerializeObject(newPost);
         var content = new StringContent(json, Encoding.UTF8, "application/json");

         HttpResponseMessage response = await client.PostAsync("posts", content);

         if (response.IsSuccessStatusCode) {
            string data = await response.Content.ReadAsStringAsync();
            Console.WriteLine("\nPOST Response:\n" + data + "\n");
         } else {
            Console.WriteLine($"POST failed: {response.StatusCode}");
         }
      }

      //  PUT: Update a post 
      static async Task UpdatePostAsync() {
         Console.WriteLine("PUT: Updating an existing post...");

         var updatedPost = new Post {
            Id = 1,
            UserId = 1,
            Title = "Updated Title via PUT",
            Body = "This post has been updated using PUT request."
         };

         var json = JsonConvert.SerializeObject(updatedPost);
         var content = new StringContent(json, Encoding.UTF8, "application/json");

         HttpResponseMessage response = await client.PutAsync("posts/1", content);

         if (response.IsSuccessStatusCode) {
            string data = await response.Content.ReadAsStringAsync();
            Console.WriteLine("\nPUT Response:\n" + data + "\n");
         } else {
            Console.WriteLine($"PUT failed: {response.StatusCode}");
         }
      }

      //  DELETE: Remove a post 
      static async Task DeletePostAsync() {
         Console.WriteLine("DELETE: Deleting a post...");

         HttpResponseMessage response = await client.DeleteAsync("posts/1");

         if (response.IsSuccessStatusCode) {
            Console.WriteLine("\nDELETE successful.\n");
         } else {
            Console.WriteLine($"DELETE failed: {response.StatusCode}");
         }
      }
   }
}

Output − Use this command "dotnet run" to run the application −

** Testing REST API Calls with HttpClient **

GET: Fetching posts...

GET Response:
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita ...

POST: Creating a new post...

POST Response:
{
  "Id": 0,
  "UserId": 1,
  "Title": "Testing HttpClient POST",
  "Body": "This is a dummy post created using HttpClient.",
  "id": 101
}

PUT: Updating an existing post...

PUT Response:
{
  "Id": 1,
  "UserId": 1,
  "Title": "Updated Title via PUT",
  "Body": "This post has been updated using PUT request.",
  "id": 1
}

DELETE: Deleting a post...

DELETE successful.


** All operations completed successfully! **

Conclusion

The C# library HttpClient supports all CRUD actions, such as GET, POST, PUT, and DELETE. This makes it easier to make REST API calls and smooth communication with web services, making your applications faster, more connected, and easier to integrate with external APIs.

Advertisements