31
Lesson 31 of 35 ยท Advanced

REST APIs & HttpClient

Modern applications constantly communicate over HTTP. HttpClient is .NET's built-in HTTP client. Combined with System.Text.Json, it makes consuming REST APIs straightforward.

Making GET Requests

Create a single HttpClient instance (or use IHttpClientFactory in ASP.NET). Call GetStringAsync or GetFromJsonAsync<T>.

GET request GetRequest.cs
using System.Net.Http;
using System.Net.Http.Json;

// Data models matching the API response
public record Post(int UserId, int Id, string Title, string Body);

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

// Deserialises JSON automatically
var post = await client.GetFromJsonAsync("posts/1");
Console.WriteLine(post?.Title);

POST, PUT, DELETE

PostAsJsonAsync, PutAsJsonAsync, and DeleteAsync map directly to the HTTP verbs.

POST request PostRequest.cs
var newPost = new { UserId = 1, Title = "Hello API", Body = "Testing POST" };

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

var created = await response.Content.ReadFromJsonAsync();
Console.WriteLine($"Created ID: {created?.Id}");

Error Handling & Retry

Always handle HttpRequestException. For production apps, use Polly or .NET 8+ built-in resilience extensions for automatic retries.

Error handling HttpError.cs
try
{
    var data = await client.GetFromJsonAsync("posts/9999");
}
catch (HttpRequestException ex) when ((int?)ex.StatusCode == 404)
{
    Console.WriteLine("Post not found.");
}
catch (HttpRequestException ex)
{
    Console.WriteLine($"HTTP error: {ex.StatusCode}");
}
catch (TaskCanceledException)
{
    Console.WriteLine("Request timed out.");
}