FastAPI Routes and Parameters

Build real FastAPI routes: path parameters whose type hints turn text into numbers, query parameters for filters and options, a 404 with HTTPException, a first request body for adding things, and routers that keep each resource in its own file. Then build a board game café's API and finish Module 1 ready for its book club project.

Updated

Parameters in FastAPI

  1. Path Parameters and Their Types (Apprentice): A path parameter such as {game_id} lets one FastAPI route answer every address of its shape, its type hint turns the text from the address into a number, FastAPI answers 422 when it can't, and a fixed path such as /games/today goes above the path parameter that would catch it.
  2. Query Parameters: Filters and Options (Apprentice): A FastAPI function parameter that isn't in the route's path is read from the query string, so a default of None makes an optional filter, a bool reads yes-or-no values such as true and 0, and several filters combine in one request.

Answers and Bodies

  1. When It Isn't There: HTTPException and 404 (Apprentice): A FastAPI route answers 404 for an item that isn't there by raising HTTPException with a status code and a detail message, which stops the function at once and sends {"detail": ...}, and a route that creates something sets status_code=201 on its decorator.
  2. Taking JSON In: Your First Request Body (Apprentice): A POST route takes the JSON a request sends in its body through a small Pydantic model, a class that names each field and its type, then turns it into a dictionary with model_dump(), gives the new item the next id, and answers 201 with it.

Organizing Routes

  1. Organizing Routes with APIRouter (Journeyman): APIRouter moves each resource's routes into its own file in a routers package, with a prefix that starts every path and a tag that groups them on the docs page, and app.include_router wires each one in, so main.py only puts the app together.

Exercise: Board Game Shelf API

  1. Exercise: Board Game Shelf API (Apprentice): Finish the board game café's FastAPI games router, which lists the shelf with filters for group size and playing time, finds one game by its id with a 404 when there's none, and adds a game with a 201, and let TestClient's tests check every answer.

Up Next: Models and Validation

  1. Up Next: Models and Validation (Apprentice): Look back at what Module 1 taught you, see a project that puts all of it to work, a book club's API, and see the gaps Module 2 closes, with Pydantic models and field rules that check every request, one clear shape for every error, and tests that prove the API works.