Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 42 ยท Projects and Practice

Project: Weather App

Build a .NET MAUI weather app: call a REST API with HttpClient, parse JSON into models, handle errors and offline use, cache results and show loading states, with a runnable fake-server stand-in.

A weather app teaches the other half of mobile development: talking to a server. You call a web API, turn JSON into objects, show a loading state, handle failures (no signal is normal on a phone) and cache the last result so the app is useful offline. In this project you build the whole data layer and the view model; the MAUI pages are shown read-only.

The site cannot run MAUI, and your learners' code cannot reach real weather servers from the sandbox (it has no network). The service here is written against HttpClient, exactly as in a real app, but the runnable examples plug in a fake HTTP handler that returns canned JSON. That is also how you test a real app without the network.

Plan

flowchart TD
    P["WeatherPage"] --> VM["WeatherViewModel"]
    VM --> S["WeatherService (HttpClient)"]
    VM --> C["Cache (Preferences or file)"]
    S --> API[("Weather API")]

Flow: the view model asks the service; on failure it falls back to the cache and tells the user.

Features: search a city, show temperature, conditions and a 3-day forecast, use cached data when offline, pull to refresh, and switch between Celsius and Fahrenheit.

The JSON and the models

Most weather APIs return something like this (the exact fields depend on the provider; this is a simplified design of our own):

JSON
{
  "city": "Lisbon",
  "current": { "tempC": 19.5, "condition": "Partly cloudy", "windKph": 14 },
  "forecast": [
    { "date": "2026-05-02", "highC": 21, "lowC": 13, "condition": "Sunny" },
    { "date": "2026-05-03", "highC": 18, "lowC": 12, "condition": "Rain" }
  ]
}

Matching models, using System.Text.Json:

C#
public record Current(double TempC, string Condition, double WindKph);
public record Day(DateOnly Date, double HighC, double LowC, string Condition);
public record Weather(string City, Current Current, List<Day> Forecast);

For trimming and Native AOT, add a source-generated context so no reflection is needed:

C#
[JsonSerializable(typeof(Weather))]
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
internal partial class WeatherJsonContext : JsonSerializerContext { }

The service

The service wraps HttpClient. Registering HttpClient through the factory (builder.Services.AddHttpClient<WeatherService>(...)) gives you pooling and one place to set the base address. The important design choices:

  • one method returns a typed result, not raw JSON,
  • a timeout and a cancellation token so the UI never hangs,
  • distinguish "not found" (user error) from "cannot connect" (network error).

Here is the service with a fake server, runnable:

C# Stand-in: weather service with a fake HTTP server

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.

The fake handler is the key testing tool: a real HttpClient with a controlled transport. In the app, AddHttpClient provides the real handler; in tests you build the client yourself with a fake one.

Unit conversion

Keep temperature in one unit (Celsius) in the model, and convert only for display, because conversion is a presentation setting:

C#
public static double ToFahrenheit(double c) => c * 9 / 5 + 32;

The view model: loading, error, cache

The view model has four states: Idle, Loading, Loaded and Error, and one rule: never leave the user with an empty screen if there is something cached. It also cancels an older request when a new search starts, so a slow answer for the previous city cannot overwrite a fast answer for the new one.

C# Stand-in: view model with cache and cancellation

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.

Notice the order of the catch clauses: the one with the when filter handles "network error but we have a cached value" first.

The page

XML
<ContentPage x:DataType="vm:WeatherViewModel" Title="Weather">
    <RefreshView IsRefreshing="{Binding IsRefreshing}" Command="{Binding RefreshCommand}">
        <ScrollView>
            <VerticalStackLayout Padding="16" Spacing="12">
                <SearchBar Placeholder="City" Text="{Binding City}" SearchCommand="{Binding SearchCommand}" />

                <ActivityIndicator IsRunning="{Binding IsLoading}" IsVisible="{Binding IsLoading}" />

                <Label Text="{Binding Message}" TextColor="DarkOrange" IsVisible="{Binding HasMessage}" />

                <VerticalStackLayout IsVisible="{Binding HasWeather}">
                    <Label Text="{Binding City}" FontSize="28" />
                    <Label Text="{Binding Temperature}" FontSize="56" />
                    <Label Text="{Binding Condition}" />
                    <Switch IsToggled="{Binding UseFahrenheit}" />
                </VerticalStackLayout>

                <CollectionView ItemsSource="{Binding Days}" HeightRequest="200">
                    <!-- three-day forecast rows -->
                </CollectionView>
            </VerticalStackLayout>
        </ScrollView>
    </RefreshView>
</ContentPage>

Persist the last result with Preferences (small JSON) or a file in FileSystem.CacheDirectory, and the last used city so the app opens straight to useful content. Use Connectivity.Current.NetworkAccess to decide early whether to bother calling the network (see Connectivity and Sensors), but still handle exceptions: connectivity checks can be wrong.

API keys do not belong in the app: a key shipped inside an app can be extracted. Put a small backend between the app and the provider, or use a provider that offers restricted, per-app keys.

Extension ideas

  1. Location button using Geolocation.GetLocationAsync, then call the API by coordinates.
  2. An hourly chart with GraphicsView.
  3. Favorite cities saved in SQLite.
  4. A home-screen widget (platform specific code).
  5. Weather alerts as local notifications.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why test an HttpClient-based service with a fake HttpMessageHandler?

    A fake handler is a real HttpClient transport that returns canned responses, so tests are fast, offline and deterministic.
  2. 2. What is the benefit of cancelling the previous request when a new search starts?

    Without cancellation, responses can arrive out of order and show the wrong city.
  3. 3. Which unit should the model store temperatures in?

    Storing one unit avoids inconsistencies; the view model converts for presentation.
  4. 4. Why should an API key not be embedded in the app?

    Apps can be unpacked and inspected. Use a backend you control or restricted per-app keys.

Summary

  • A typed service over HttpClient returns results (ok, not found, network error) instead of raw responses.
  • System.Text.Json (ideally source generated) maps JSON to records.
  • The view model has explicit states, a cache fallback and cancellation of stale requests.
  • A fake HttpMessageHandler makes network code testable.
  • Secrets stay on the server.

Next: Project: Expense Tracker