Fetching Data & API Integration
7 min read
Fetching Data & API Integration 📡
Welcome back, coder! 👋 If you thought building static layouts was fun, wait until you connect your app to the "real world."
A Blazor application without data is like a Ferrari without an engine—it looks great in the driveway, but it's not taking you to the grocery store. Today, we are learning how to make your app talk to servers, fetch data, and handle the chaos of the internet.
We will cover the HttpClient, consuming REST APIs, handling CRUD (Create, Read, Update, Delete), and managing Loading States so your users don't think your app has frozen.
1. Setting up and Configuring HttpClient 🛠️
The Definition
HttpClient is a class in the .Net ecosystem used for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
The Problem
You have a Blazor app, and you have a database (or an API) somewhere else. How do you bridge the gap? You might be tempted to just create a new connection every time you need data.
⚠️ Stop! Creating a new HttpClient() manually inside your components is a common rookie mistake. It leads to socket exhaustion, where your server runs out of ports to talk to the outside world. It’s like buying a brand new smartphone every time you want to make a single phone call, then throwing it in the trash. Expensive and wasteful.
The Solution: Dependency Injection (DI)
In Blazor, we use Dependency Injection to manage the HttpClient. The framework creates it once (or manages a pool of them) and hands it to your component when asked.
How to Set It Up
The setup differs slightly between Blazor WebAssembly (WASM) and Blazor Server.
A. Blazor WebAssembly (Client-side)
In WASM, the browser creates the request. We configure the client to look at the host address.
File: Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
// Industry Standard: Register HttpClient with the BaseAddress
builder.Services.AddScoped(sp => new HttpClient {
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
await builder.Build().RunAsync();B. Blazor Server (Server-side)
In Server apps, the server makes the request. You often need to register the HttpClient explicitly, usually pointing to a specific base URL (like a separate backend API).
File: Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
// Register HttpClient
builder.Services.AddHttpClient();
var app = builder.Build();
// ... rest of the pipelineInjecting it into a Component
Once configured in Program.cs, you can use it in any .razor file using the @inject directive.
@page "/fetch-data"
@using System.Net.Http // Required namespace
@inject HttpClient Http // Give me the instance!
<h3>I am ready to fetch data!</h3>
@code {
// Logic goes here
}Fun Fact: In the early days of .NET, developers didn't realize
HttpClientwas designed to be reused. They treated it like a disposable napkin. This caused so many server crashes that Microsoft had to write huge documentation specifically saying, "Please stop throwing away your HttpClients."
2. Making GET Requests to External REST APIs 📥
The Definition
A GET request is an HTTP method used to request data from a specified resource. It reads data without changing it.
The Problem
You have your HttpClient ready, but your page is empty. You need to pull a list of items (like weather forecasts, stocks, or cat facts) from an API.
The Solution: GetFromJsonAsync
The modern, industry-standard way to fetch data in Blazor is using the System.Net.Http.Json extension methods. It automatically handles the connection, reads the data, and converts (deserializes) the JSON text into a C# object.
Step-by-Step Implementation
1. Create a Data Model (DTO)
Always define what the data looks like first.
// Models/TodoItem.cs
public class TodoItem
{
public int Id { get; set; }
public string? Title { get; set; }
public bool Completed { get; set; }
}2. Fetch the Data
We use the OnInitializedAsync lifecycle method. This is the perfect place to load data when the component first renders.
@page "/todo-list"
@inject HttpClient Http
<h3>My To-Do List</h3>
<ul>
@foreach (var todo in todos)
{
<li>@todo.Title (@(todo.Completed ? "✅" : "❌"))</li>
}
</ul>
@code {
// Initialize an empty list so the loop doesn't crash on null
private List<TodoItem> todos = new();
protected override async Task OnInitializedAsync()
{
// This URL is a free fake API for testing
todos = await Http.GetFromJsonAsync<List<TodoItem>>("https://jsonplaceholder.typicode.com/todos")
?? new List<TodoItem>();
}
}Note:
GetFromJsonAsyncis "awaitable." This means the code pauses there (freeing up the thread) until the internet comes back with your data.
3. Performing CRUD Operations (POST, PUT, DELETE) 📝
The Definition
CRUD stands for Create, Read, Update, and Delete. These are the four basic functions of persistent storage.
The Problem
Reading data (GET) is nice, but eventually, you need to send data back to the server to save changes.
The Solution: The JSON Extension Methods
Blazor provides helper methods that make sending JSON easy.
A. Create (POST)
POST sends data to the server to create/append a resource.
- Method:
PostAsJsonAsync
private async Task AddTodo()
{
var newTodo = new TodoItem { Title = "Learn Blazor", Completed = false };
// Arguments: The API Endpoint, and the Object to send
var response = await Http.PostAsJsonAsync("https://api.example.com/todos", newTodo);
if (response.IsSuccessStatusCode)
{
// Ideally, fetch the list again or add the item to the local list
Console.WriteLine("Item added!");
}
}B. Update (PUT)
PUT replaces a resource with new data.
- Method:
PutAsJsonAsync
private async Task UpdateTodo(TodoItem item)
{
item.Completed = true;
// Usually, the URL includes the ID of the item being updated
await Http.PutAsJsonAsync($"https://api.example.com/todos/{item.Id}", item);
}C. Delete (DELETE)
DELETE removes the resource.
- Method:
DeleteAsync
private async Task DeleteTodo(int id)
{
// Simply call delete on the specific ID
await Http.DeleteAsync($"https://api.example.com/todos/{id}");
}Simulation: Imagine a restaurant.
- GET: You look at the menu.
- POST: You give the waiter your order (creating a ticket).
- PUT: You change your mind and ask for steak instead of salad (updating the ticket).
- DELETE: You walk out because the prices are too high (destroying the ticket).
4. Handling Loading States, Async Operations, and Errors ⏳
The Problem
Internet speed varies. APIs crash. Satellites drift.
If you don't handle the "waiting time" (latency), your user sees a blank screen. If the API fails and you don't catch the error, your app crashes silently, and the user stares at a frozen button thinking, "Is it me?"
The Solution: State Variables
We track the state of the request using simple variables (isLoading, errorMessage) and render the UI conditionally.
Industry Standard Pattern
Here is a robust pattern used in real-world applications:
@page "/robust-fetch"
@inject HttpClient Http
<h3>Weather Forecast</h3>
@if (isLoading)
{
<!-- 1. Loading State -->
<p><em>Loading... (Patience is a virtue 🐢)</em></p>
}
else if (!string.IsNullOrEmpty(errorMessage))
{
<!-- 2. Error State -->
<div class="alert alert-danger">
<strong>Error:</strong> @errorMessage
</div>
}
else
{
<!-- 3. Data State -->
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp (C)</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[]? forecasts;
private bool isLoading = true; // Start as loading
private string? errorMessage = null;
protected override async Task OnInitializedAsync()
{
try
{
// Simulate a delay so you can actually see the loading message
await Task.Delay(1000);
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}
catch (HttpRequestException ex)
{
// Network errors (404, 500, DNS fail)
errorMessage = $"Could not fetch data. Server said: {ex.Message}";
}
catch (Exception ex)
{
// Generic errors (JSON parsing fail, null reference)
errorMessage = $"Something went wrong: {ex.Message}";
}
finally
{
// Always turn off loading, whether it worked or failed
isLoading = false;
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
}
}Why this matters
- UX (User Experience): Users need feedback. A spinning loader tells them "I'm working on it," not "I'm broken."
- Safety: wrapping API calls in
try-catchblocks prevents the whole app from crashing ("Unhandled Exception") just because the Wi-Fi blinked.
🧠 Quick Review
- Don't
new HttpClient(). Do use@inject HttpClient. - GET retrieves data (
GetFromJsonAsync). - POST/PUT/DELETE modifies data (
PostAsJsonAsync, etc.). - Always handle loading states and potential errors.
Now go forth and connect your apps to the world! 🌍
🔗 References & Further Reading
Challenge
Challenge: Blazor Product Management Component
You are tasked with building a full CRUD (Create, Read, Update, Delete) component for managing a list of products. Your component must interact with a REST API and handle loading and error states gracefully.
Requirements:
Data Transfer Object (DTO): Inside the
@codeblock, define a public class namedProductwith the following properties:public int Id { get; set; }public string Name { get; set; }public decimal Price { get; set; }
State Management:
- Declare a private field to hold a list of
Productobjects. - Declare a private boolean field named
isLoadingto track the state of API calls. Initialize it totrue. - Declare a private string field named
errorMessageto hold any potential error messages.
- Declare a private field to hold a list of
Fetch Products (Read):
- Override the
OnInitializedAsynclifecycle method. - Implement a
try-catch-finallyblock to fetch the product data. - Inside the
tryblock, use the injectedHttpClientto perform a GET request to/api/productsusingGetFromJsonAsync. Assign the result to your product list. - The
catchblock should capture any exception and set theerrorMessage. - The
finallyblock must setisLoadingtofalse.
- Override the
Create, Update, and Delete Operations:
AddProduct: This method should accept aProductobject and send it to the/api/productsendpoint usingPostAsJsonAsync.UpdateProduct: This method should accept aProductobject and send it to the/api/products/{id}endpoint usingPutAsJsonAsync.DeleteProduct: This method should accept anint idand send a request to the/api/products/{id}endpoint usingDeleteAsync.- After each successful CUD operation, you should refresh the product list by calling the data fetching logic again.
Expected result
Your final code should be a complete Blazor component (.razor file) that fulfills all the requirements. The @code block should contain:
- A
public class ProductwithId,Name, andPriceproperties. - Private fields:
private List<Product> products = new();,private bool isLoading = true;, andprivate string errorMessage;. - A fully implemented
OnInitializedAsyncmethod. It must contain atry-catch-finallyblock that callsHttp.GetFromJsonAsync<List<Product>>("/api/products"), assigns the result to theproductslist, setserrorMessageon failure, and setsisLoadingtofalsein thefinallyblock. - An
AddProductmethod that usesHttp.PostAsJsonAsync("/api/products", newProduct)and then reloads the data. - An
UpdateProductmethod that usesHttp.PutAsJsonAsync($"/api/products/{productToUpdate.Id}", productToUpdate)and then reloads the data. - A
DeleteProductmethod that usesHttp.DeleteAsync($"/api/products/{id}")and then reloads the data.