Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 42 ยท Data and Storage

Consuming REST APIs

Call web APIs from a .NET MAUI app with HttpClient and IHttpClientFactory, parse JSON with System.Text.Json, handle errors, retries and offline cache, and test with a fake handler.

Most real apps talk to a server: product lists, weather, chat messages, sign-in. In .NET MAUI you use the same HttpClient and System.Text.Json as any other .NET app. What is different on a phone is everything around the call: the network may disappear, the user may switch apps mid-request, and the emulator cannot reach localhost the way you expect. This lesson covers the setup and the patterns that make API code reliable.

The runnable examples use a fake HttpMessageHandler, so no real network is needed. That is also exactly how you unit test API code. The MAUI-specific parts (registration, emulator addresses, platform security settings) are shown read-only.

Registering a typed client

Do not create new HttpClient() in every method. Register one through IHttpClientFactory, which reuses connections correctly:

C#
// MauiProgram.cs
builder.Services.AddHttpClient<WeatherService>(client =>
{
    client.BaseAddress = new Uri("https://api.example.com/");
    client.Timeout = TimeSpan.FromSeconds(15);
    client.DefaultRequestHeaders.Add("Accept", "application/json");
});
C#
public class WeatherService(HttpClient http)
{
    public async Task<Forecast?> GetForecastAsync(string city, CancellationToken ct = default)
    {
        using var response = await http.GetAsync($"forecast?city={Uri.EscapeDataString(city)}", ct);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<Forecast>(cancellationToken: ct);
    }
}

public record Forecast(string City, double TemperatureC, string Summary);

ReadFromJsonAsync (from System.Net.Http.Json) deserializes in one call. It uses web defaults, so JSON in camelCase (temperatureC) maps to your PascalCase properties without any attribute.

Always escape user text with Uri.EscapeDataString, accept a CancellationToken, and let the caller cancel when the user leaves the page.

Sending data

C#
var order = new NewOrder("Mia", 3);
using var response = await http.PostAsJsonAsync("orders", order, ct);

if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
    var problem = await response.Content.ReadFromJsonAsync<ValidationProblem>(cancellationToken: ct);
    // show problem.Errors next to the form fields
}

For PUT, PATCH and DELETE, use PutAsJsonAsync, PatchAsJsonAsync (in newer versions) and DeleteAsync. Send an Authorization: Bearer ... header with request.Headers.Authorization, reading the token from secure storage.

Phones are not servers: the traps

  • Emulator addresses. The Android emulator reaches your computer at 10.0.2.2, not localhost. iOS simulators and Windows can use localhost.
  • HTTPS and dev certificates. A local ASP.NET Core dev certificate is not trusted by the Android emulator. Use a development-only handler that accepts it, and never ship that handler.
  • Cleartext HTTP. Android blocks plain http:// unless you opt in with a network security config; iOS blocks it through App Transport Security. Use HTTPS in production.
  • Timeouts. A phone on a train can stall forever. Always set a timeout and always handle TaskCanceledException.
  • No connection. Check Connectivity.Current.NetworkAccess for a friendly message (connectivity), but still catch HttpRequestException, because "connected" does not mean "reachable".
  • Threading. await returns on the UI thread in a page or view model, which is convenient. Do heavy parsing in Task.Run for big payloads.

A result type instead of exceptions

Exceptions for expected failures (offline, 404) make view models messy. Return a result that says what happened:

C#
public abstract record ApiResult<T>
{
    public sealed record Ok(T Value) : ApiResult<T>;
    public sealed record Failed(string Message, bool CanRetry) : ApiResult<T>;
}

The view model then switches on the result and sets IsBusy, Error and Items accordingly.

Retries with backoff

Transient errors (timeouts, 502, 503) often succeed on a second try. A simple exponential backoff waits 1 s, 2 s, 4 s between attempts. In production the Microsoft.Extensions.Http.Resilience package provides ready-made policies (AddStandardResilienceHandler()), but understanding the loop first is useful.

Try it: a client with a fake server, retries and caching

The fake handler fails the first two calls with 503 and then succeeds. The service retries, and an in-memory cache returns the last good value if every attempt fails.

C# Stand-in: HttpClient with a fake handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three behaviors to notice: transient 503s are retried, a 404 is not retried (it will never succeed), and when every attempt fails the cached value keeps the screen useful.

Cancellation: stop work when the user leaves

A request the user no longer cares about wastes battery and data. Pass the CancellationToken all the way down, and cancel it when the page disappears or the search text changes.

C# Stand-in: cancelling a stale search

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Only the last search completes. In a real app the token goes into http.GetAsync(url, token). This pattern pairs well with a short debounce, as in the connectivity lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use IHttpClientFactory rather than new HttpClient() per call?

    The factory reuses handlers correctly, avoiding socket exhaustion and stale DNS, and centralizes configuration.
  2. 2. From the Android emulator, how do you reach a server on your development computer?

    Inside the Android emulator localhost is the emulator itself; 10.0.2.2 is the host computer.
  3. 3. Which failure should NOT be retried?

    A 404 will not change on retry. Transient failures such as 503 and timeouts are worth retrying.
  4. 4. What is the benefit of a fake HttpMessageHandler?

    A fake handler returns canned responses, so tests are fast, deterministic and offline.

Summary

  • Register typed clients with AddHttpClient, set a base address and a timeout, and pass CancellationTokens.
  • Use GetFromJsonAsync/ReadFromJsonAsync and PostAsJsonAsync for JSON.
  • Plan for the phone: emulator addresses, HTTPS, offline, timeouts and retries.
  • Return result types, cache the last good value, and test with a fake handler.

Next: Resources and Styles