🏠 VisualStudioTutor.com  ·  C# Tutorial Home  ·  C# Lesson 21 of 40
Lesson 21 of 40 Networking Advanced ⏱ 35 min

HttpClient & REST API Consumption

Call REST endpoints asynchronously, deserialize JSON responses into C# records, and handle unsuccessful HTTP responses correctly.

Part 1: What You Will Learn

Call REST endpoints asynchronously, deserialize JSON responses into C# records, and handle unsuccessful HTTP responses correctly.

  • Configure an HttpClient with a BaseAddress.
  • Send GET and POST requests asynchronously.
  • Deserialize JSON with `GetFromJsonAsync<T>()`.
  • Use `EnsureSuccessStatusCode()` so HTTP failures are not silently treated as success.

Project setup: Create a .NET 10 Console App. The example uses the public JSONPlaceholder test API and the built-in `System.Net.Http.Json` APIs.

Part 2: Topic-Specific Working Example

The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.

using System.Net.Http.Json;

public record Post(int Id, int UserId, string Title, string Body);

using HttpClient client = new()
{
    BaseAddress = new Uri("https://jsonplaceholder.typicode.com/")
};

// GET /posts/1
Post? post = await client.GetFromJsonAsync<Post>("posts/1");

if (post is not null)
{
    Console.WriteLine($"#{post.Id}: {post.Title}");
}

// POST /posts
var newPost = new
{
    userId = 1,
    title = "Learning HttpClient",
    body = "Calling REST APIs from C#."
};

HttpResponseMessage response =
    await client.PostAsJsonAsync("posts", newPost);

response.EnsureSuccessStatusCode();

Post? created = await response.Content.ReadFromJsonAsync<Post>();
Console.WriteLine($"Server returned ID: {created?.Id}");

Part 3: How the Code Works

  • `GetFromJsonAsync<T>()` combines an HTTP GET request with JSON deserialization.
  • `PostAsJsonAsync()` serializes the anonymous object to JSON and sends it as the request body.
  • `EnsureSuccessStatusCode()` throws an exception for non-success HTTP status codes.
  • For larger applications, prefer `IHttpClientFactory` or typed clients instead of repeatedly constructing clients throughout the codebase.

Part 4: Mini Project & Practice

Mini project: consume a weather or public data API. Display the HTTP status, deserialize the response into records, and handle cancellation and network errors with try/catch.

Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.

When you are comfortable with this lesson, continue to Lesson 22.

C# in Visual Studio 2026

📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition