Prerequisites
- Basic knowledge of Blazor Server
- Visual Studio or VS Code
- .NET 6 or .NET 8 SDK
- A sample REST API (we'll use JSONPlaceholder
Step 1. Create a Blazor Server App.
- Open Visual Studio
- Create a new Blazor Server App
- Name it BlazorRestClientDemo
Step 2. Create the Model.
public class Post
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
Step 3. Register HttpClient in Program.cs.
builder.Services.AddHttpClient("API", client =>
{
client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
});
Step 4. Create a Service to Call the API.
public class PostService
{
private readonly HttpClient _http;
public PostService(IHttpClientFactory factory)
{
_http = factory.CreateClient("API");
}
public async Task<List<Post>> GetPostsAsync()
{
var response = await _http.GetFromJsonAsync<List<Post>>("posts");
return response!;
}
public async Task<Post?> GetPostAsync(int id)
{
return await _http.GetFromJsonAsync<Post>($"posts/{id}");
}
public async Task<Post?> CreatePostAsync(Post post)
{
var response = await _http.PostAsJsonAsync("posts", post);
return await response.Content.ReadFromJsonAsync<Post>();
}
}
Step 5. Register the Service and Program.cs.
builder.Services.AddScoped<PostService>();
Step 6. Use in a Razor Component.
@page "/posts"
@inject PostService PostService
<h3>All Posts</h3>
@if (posts == null)
{
<p>Loading...</p>
}
else
{
<ul>
@foreach (var post in posts)
{
<li><b>@post.Title</b> - @post.Body</li>
}
</ul>
}
@code {
private List<Post>? posts;
protected override async Task OnInitializedAsync()
{
posts = await PostService.GetPostsAsync();
}
}
Add a simple form and call CreatePostAsync().
Conclusion
Blazor Server apps can easily consume REST APIs using HttpClient and typed models. In this article, you learned how to,
- Register and inject HttpClient
- Call GET and POST endpoints
- Display data in the UI
Blazor is a powerful front-end technology, and now you know how to connect it with real-world APIs.