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
-
Creating a dedicated service
-
Handling responses (including errors)
-
Types of requests (GET / POST)
-
JSON Serialization / Deserialization
-
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
🧩 Service: PostService.cs
🧱 Registration in Program.cs
🖥️ Blazor Component: Posts.razor
🧠 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.