RO EN
Interaction with external APIs (HttpClient)
Doru Bulubasa
30 May 2025

Blazor WebAssembly comes with built-in support for HttpClient, which allows your application to communicate with external RESTful APIs. In this article, we explore how to do this correctly, with a real example and service separation.


🔧 What is HttpClient?

HttpClient is a class in .NET used to send HTTP requests to a server. In Blazor WebAssembly, it is automatically injected with a basic configuration (rooted at your site's address). For requests to external domains, you need to set the BaseAddress manually.


✅ Recommended Steps

  1. Creating a dedicated service

  2. Handling responses (including errors)

  3. Types of requests (GET / POST)

  4. JSON Serialization / Deserialization

  5. Usage with async/await and UI feedback


🧪 Example: Consuming a Public Posts API

We will use JSONPlaceholder to get a list of posts.


📁 Model: Post.cs

public class Post
{
    public int UserId { get; set; }
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Body { get; set; } = string.Empty;
}


🧩 Service: PostService.cs

public class PostService
{
    private readonly HttpClient _http;

    public PostService(HttpClient http)
    {
        _http = http;
    }

    public async Task<List<Post>> GetPostsAsync()
    {
        try
        {
            var response = await _http.GetAsync("https://jsonplaceholder.typicode.com/posts");
            response.EnsureSuccessStatusCode();
            var json = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<List<Post>>(json) ?? new();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"API Error: {ex.Message}");
            return new();
        }
    }
}


🧱 Registration in Program.cs

builder.Services.AddScoped<PostService>();


🖥️ Blazor Component: Posts.razor

@page "/posts"
@inject PostService PostService

<h3>Posts List</h3>

@if (posts is null)
{
    <p>Loading...</p>
}
else
{
    <ul>
        @foreach (var post in posts)
        {
            <li><strong>@post.Title</strong>: @post.Body</li>
        }
    </ul>
}

@code {
    private List<Post>? posts;

    protected override async Task OnInitializedAsync()
    {
        posts = await PostService.GetPostsAsync();
    }
}


🧠 Best Practices

  • Use dedicated services for HTTP calls

  • Handle API errors with try/catch and informative messages

  • Don't forget HttpClientFactory in Blazor Server or .NET MAUI applications

  • For POST/PUT, use JsonContent.Create() starting with .NET 8


Want to communicate with your own API? You can start here and then integrate with your ASP.NET Core backend.