Link Search Menu Expand Document

6. Create an HTTP Client: Exercise

You’re going to create a console application that connects to the Autobarn API.

Create a new console application:

dotnet new console -o Autobarn.Client
dotnet sln add Autobarn.Client

Requirements:

When you run the application, it’ll display a list of commands. A command is invoked by pressing the corresponding key:

Welcome to the Autobarn API Client
Press a key to run an API command:

k:	List all vehicle makes
d: 	List all vehicle models
c:  Clear all cached data
x:	Exit

Your client should use idiomatic .NET configuration with a single configuration value AutobarnApiRootUrl defined in appsettings.json with the value https://autobarn.dev/api/

Your client must follow hypermedia links from the discovery endpoint, and must follow hypermedia conventions when retrieving data that’s exposed as a paged dataset.

To list all vehicle makes:

  1. Query the API discovery endpoint, find the link labelled makes
  2. Follow this link, retrieve the list of makes
  3. While the result contains a link labelled next, retrieve the next set of makes and add them to your result
  4. When you reach a result without a next link, you’re at the end.

To list all vehicle models, you need to traverse via the models link included in each make resource:

  1. Query the API discovery endpoint, find the link labelled makes
  2. Follow this link, retrieve the list of makes
  3. For each result in that list:
    1. Find the models link
    2. Retrieve the results of that link
    3. If the models result includes a next link, follow it and add it to the result (the same pagination loop as we’ve used elsewhere)
  4. If the makes resource includes a next link, follow it and repeat

Makes and models should be retrieved on first use, and should be cached in memory so that your client doesn’t retrieve them every time.

The user should be able to clear this in-memory cache by pressing c.

Keyboard commands are a single keypress (c, not c + Enter), and are case insensitive (we’re matching the key, not the character)

Extras:

  • Measure the elapsed time between the keypress and completing the task. Print this to the console output in milliseconds.

Hints

  • Use the System.Net.HttpClient class to make HTTP requests and handle responses; you’ll find lots of information about how to use this class at https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient

  • Wrap the raw HttpClient in a wrapper class which exposes strongly-typed methods that abstract away the HTTP details in favour of business-level operations:

    public class AutobarnApiClient(HttpClient http) {
      	public List<VehicleMake> ListVehicleMakes() {
            // TODO: list all vehicle makes
        }
    }