Learn Blazor · 10/15

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

csharp
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

csharp
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 pipeline

Injecting it into a Component

Once configured in Program.cs, you can use it in any .razor file using the @inject directive.

razor
@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 HttpClient was 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.

csharp
// 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.

razor
@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: GetFromJsonAsync is "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
csharp
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
csharp
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
csharp
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:

razor
@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

  1. UX (User Experience): Users need feedback. A spinning loader tells them "I'm working on it," not "I'm broken."
  2. Safety: wrapping API calls in try-catch blocks prevents the whole app from crashing ("Unhandled Exception") just because the Wi-Fi blinked.

🧠 Quick Review

  1. Don't new HttpClient(). Do use @inject HttpClient.
  2. GET retrieves data (GetFromJsonAsync).
  3. POST/PUT/DELETE modifies data (PostAsJsonAsync, etc.).
  4. 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:

  1. Data Transfer Object (DTO): Inside the @code block, define a public class named Product with the following properties:

    • public int Id { get; set; }
    • public string Name { get; set; }
    • public decimal Price { get; set; }
  2. State Management:

    • Declare a private field to hold a list of Product objects.
    • Declare a private boolean field named isLoading to track the state of API calls. Initialize it to true.
    • Declare a private string field named errorMessage to hold any potential error messages.
  3. Fetch Products (Read):

    • Override the OnInitializedAsync lifecycle method.
    • Implement a try-catch-finally block to fetch the product data.
    • Inside the try block, use the injected HttpClient to perform a GET request to /api/products using GetFromJsonAsync. Assign the result to your product list.
    • The catch block should capture any exception and set the errorMessage.
    • The finally block must set isLoading to false.
  4. Create, Update, and Delete Operations:

    • AddProduct: This method should accept a Product object and send it to the /api/products endpoint using PostAsJsonAsync.
    • UpdateProduct: This method should accept a Product object and send it to the /api/products/{id} endpoint using PutAsJsonAsync.
    • DeleteProduct: This method should accept an int id and send a request to the /api/products/{id} endpoint using DeleteAsync.
    • 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:

  1. A public class Product with Id, Name, and Price properties.
  2. Private fields: private List<Product> products = new();, private bool isLoading = true;, and private string errorMessage;.
  3. A fully implemented OnInitializedAsync method. It must contain a try-catch-finally block that calls Http.GetFromJsonAsync<List<Product>>("/api/products"), assigns the result to the products list, sets errorMessage on failure, and sets isLoading to false in the finally block.
  4. An AddProduct method that uses Http.PostAsJsonAsync("/api/products", newProduct) and then reloads the data.
  5. An UpdateProduct method that uses Http.PutAsJsonAsync($"/api/products/{productToUpdate.Id}", productToUpdate) and then reloads the data.
  6. A DeleteProduct method that uses Http.DeleteAsync($"/api/products/{id}") and then reloads the data.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.