APIs with FastAPI · Chapter 2 of 26

Path and query parameters

By the end of this chapter you can put values in a route's path and in its query string, give them types that FastAPI converts and checks, read the 422 a client gets for a wrong value, set limits and fixed choices, answer 404 for a thing that does not exist, and say which route FastAPI picks when two could match. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: First API
  • 4 tasks
  • FastAPI
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Chapter 1's routes answer one fixed thing: the health, the whole rate card, every serviceable pincode. Real questions name one thing, or some things. Sunita's riders keep finding parcels booked to pincodes that do not exist, so merchants should check one pincode before they book. Imran's merchants do not want all forty parcels; they want "my parcels that are out for delivery". You cannot write a route for each pincode and each merchant. A route needs inputs, and an input from the network is never what you hoped: a word where a number should be, a zone that does not exist, a limit of a million.

The lesson

A path parameter names one thing

A part of the path in braces is a path parameter. Whatever the client puts there arrives in the function argument of the same name:

from fastapi import FastAPI, HTTPException

HUBS = {
    "JPR-MN": {"name": "Malviya Nagar hub", "riders": 2},
    "JPR-VK": {"name": "Vaishali Nagar hub", "riders": 3},
}

app = FastAPI()


@app.get("/hubs/{code}")
def hub(code: str):
    if code not in HUBS:
        raise HTTPException(status_code=404, detail=f"No hub {code}")
    return {"code": code, **HUBS[code]}
$ curl -i localhost:8000/hubs/JPR-VK
HTTP/1.1 200 OK
content-type: application/json

{"code":"JPR-VK","name":"Vaishali Nagar hub","riders":3}
$ curl -i localhost:8000/hubs/JPR-XX
HTTP/1.1 404 Not Found
content-type: application/json

{"detail":"No hub JPR-XX"}

One route answers every hub. For a hub that does not exist, returning None or {} would answer 200 OK, and the merchant's software would think it worked. Raising HTTPException stops the function there and sends the status you name, with your detail in the body, in the same {"detail": ...} shape FastAPI uses for its own 404.

Types convert, and refuse

Everything in a path is text on the wire. The type you write on the argument tells FastAPI what to turn it into. Here is a route that counts the parcels booked on one day of October, from parcels.json:

@app.get("/bookings/{day}")
def bookings(day: int):
    booked = [p for p in PARCELS if int(p["booked_at"][8:10]) == day]
    return {"day": day, "parcels": len(booked)}
$ curl -s localhost:8000/bookings/12
{"day":12,"parcels":2}
$ curl -i localhost:8000/bookings/twelve
HTTP/1.1 422 Unprocessable Content
content-type: application/json

{"detail":[{"type":"int_parsing","loc":["path","day"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"twelve"}]}

"12" arrived as text and the function got the number 12. "twelve" cannot become a number, so your function never ran: Pydantic checked the value first, and FastAPI answered 422 with a list of problems. Each one says where (loc: in the path, the parameter day), what (msg), a machine-readable type, and the input it got. A merchant's developer can read exactly what they sent wrong.

Leave the type off and nothing converts. day stays the string "12", which never equals the number 12:

$ curl -s localhost:8000/bookings/12
{"day":"12","parcels":0}
$ curl -s localhost:8000/bookings/twelve
{"day":"twelve","parcels":0}

No error anywhere: a 200 with a wrong answer, the worst kind of bug. The opposite trap is just as real. A pincode looks like a number, but the files keep it as the string "302001"; declare it int and no lookup in a dictionary of strings ever matches.

Limits on a parameter

A type says what kind of value; often you need more: a day from 1 to 31, a code of a certain shape. Annotated attaches that to the type, and FastAPI's Path and Query carry the rules:

from typing import Annotated

from fastapi import Path as PathParam


@app.get("/bookings/{day}")
def bookings(day: Annotated[int, PathParam(ge=1, le=31)]):
    ...
$ curl -i localhost:8000/bookings/40
HTTP/1.1 422 Unprocessable Content
content-type: application/json

{"detail":[{"type":"less_than_equal","loc":["path","day"],"msg":"Input should be less than or equal to 31","input":"40","ctx":{"le":31}}]}

ge and le are "greater than or equal" and "less than or equal"; gt and lt leave the end out. For text, min_length, max_length and pattern (a regular expression the whole value must match) do the same. FastAPI's Path shares its name with pathlib.Path, so a file that reads data and checks paths imports one of them under another name. The rules also appear in /openapi.json, so the docs tell developers the range before they send anything.

Query parameters

An argument that is not in the path is a query parameter: it comes from the part after ?, as name=value pairs joined by &.

@app.get("/riders")
def riders(
    hub: str | None = None,
    vehicle: Vehicle | None = None,
    limit: Annotated[int, Query(ge=1, le=12)] = 5,
):
    found = [r for r in RIDERS if hub in (None, r["hub"])]
    if vehicle is not None:
        found = [r for r in found if r["vehicle"] == vehicle.value]
    return found[:limit]
$ curl -s 'localhost:8000/riders?hub=JPR-MN&vehicle=van'
[{"id":"R11","name":"Sunil Bairwa","hub":"JPR-MN","vehicle":"van"}]
$ curl -s 'localhost:8000/riders?limit=2'
[{"id":"R01","name":"Ramesh Meena","hub":"JPR-MN","vehicle":"bike"},{"id":"R02","name":"Salim Khan","hub":"JPR-MN","vehicle":"bike"}]
  • A default makes it optional: limit is 5 when the client does not send it.
  • A default of None means "not given": the route skips that filter.
  • No default makes it required. With hub: str, a bare /riders answers 422 with "type":"missing","loc":["query","hub"].

Quote the URL in the shell: an unquoted & would start a background job.

Fixed choices: an enum

DakiyaGo has three kinds of vehicle. A str would accept truck; an Enum accepts only its members:

from enum import Enum


class Vehicle(str, Enum):
    bike = "bike"
    scooter = "scooter"
    van = "van"
$ curl -i 'localhost:8000/riders?vehicle=truck'
HTTP/1.1 422 Unprocessable Content
content-type: application/json

{"detail":[{"type":"enum","loc":["query","vehicle"],"msg":"Input should be 'bike', 'scooter' or 'van'","input":"truck","ctx":{"expected":"'bike', 'scooter' or 'van'"}}]}

Inheriting from str makes each member a real string, so it turns into JSON as "van". Inside the function vehicle is a member, and vehicle.value is the plain string. The OpenAPI document now lists "enum": ["bike", "scooter", "van"], and /docs shows a drop-down instead of an empty box.

Which route answers

FastAPI keeps routes in the order the decorators ran, top to bottom. For a request it tries each one in turn and calls the first whose method and path match. A path parameter matches any text in its place. Add a second route after the bookings one:

@app.get("/bookings/today")
def today():
    return {"day": 22, "parcels": 0}
$ curl -i localhost:8000/bookings/today
HTTP/1.1 422 Unprocessable Content
content-type: application/json

{"detail":[{"type":"int_parsing","loc":["path","day"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"today"}]}

/bookings/{day} came first and its path matched today, so FastAPI chose it, tried to make today a number, and answered 422. The route written for today was never tried. Matching looks only at the path's shape; types and limits are checked after a route is chosen.

Your turn

Four tasks over DakiyaGo's data. Task 1 looks up one pincode: keep it a string, answer 404 for one that is not there and 422 for one that is not six digits. Task 2 filters parcels with optional query parameters and a limit, and task 3 makes the zone a fixed choice. Task 4 is an interview question: be ready to say why /parcels/{awb} and /parcels/summary clash, and how you fix it.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    pincodes.py: one pincode

    Merchants want to look a pincode up before they book. Make an app with one route: GET /pincodes/{pincode} answers that pincode's entry exactly as /workspace/data/pincodes.json holds it (a pincode DakiyaGo does not serve now is still one it knows, so it answers too).

    A six-digit pincode that is not in the file answers 404 with a detail that names it. A pincode that is not exactly six digits (30200, 3020011, 30200a) answers 422, refused before your function runs.

  2. Task 2

    parcels.py: find parcels

    Merchants want only some of their parcels. Make an app with one route over /workspace/data/parcels.json: GET /parcels answers {"count": N, "parcels": [...]}, with three optional query parameters: status (keep parcels with this status), merchant_id (keep this merchant's parcels) and limit (at most this many, a whole number from 1 to 100, 50 when not given).

    Every filter given must match. Keep the file's order, filter first, then cut to the limit; count is how many parcels you answer. A status no parcel has finds nothing (count 0), and a limit of 0, 101 or ten answers 422.

  3. Task 3

    zones.py: the five zones

    DakiyaGo prices by zone: local, state, metro, national and special. Make an app with one route: GET /zones/{zone} answers the zone's entry from /workspace/data/rate_card.json plus one more key, pincodes: the active pincodes in that zone (from pincodes.json), as strings, smallest first.

    Only the five zones are allowed: anything else (rural, Metro) answers 422, and the OpenAPI document lists the five values for the zone parameter, so /docs offers them as a choice.

  4. Task 4 · interview question

    Interview: parcel_routes.py, two routes and one path

    Make an app over /workspace/data/parcels.json with two routes: GET /parcels/summary answers {"total": N, "by_status": {...}}, how many parcels there are and how many of each status that appears in the file; GET /parcels/{awb} answers that parcel exactly as the file holds it, and 404 for an AWB that is not there.

    The check asks both, and /parcels/summary must reach its own route. The interviewer will ask why /parcels/{awb} and /parcels/summary clash, and how you fix it.

What you will learn

  • Path parameters: /hubs/{code}, one route for every hub.
  • Types: FastAPI converts "12" to 12, and answers 422 when it cannot.
  • Limits: Annotated with Path and Query (a range, a pattern).
  • Query parameters: ?hub=JPR-VK&limit=2, optional ones and defaults.
  • Enums for fixed choices, HTTPException for 404, and which route answers.

More in First API

Build "Path and query parameters" yourself

DakiyaGo, a Jaipur courier startup, takes bookings on WhatsApp. Merchants want an API, and you build it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.