APIs for AIFastAPI 0.141 · httpx2 2.13 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
19 small wins to finish your pathNext lesson

Path and query parameters

One endpoint should serve every ticket, not one endpoint per id. Parameters take values from the URL and hand them to your function, already converted.

Exampletickets.py
from fastapi import FastAPI

app = FastAPI()

TICKETS = {
    1: {"id": 1, "customer": "Asha", "text": "I was charged twice for one order"},
    2: {"id": 2, "customer": "Ben", "text": "My parcel has not arrived"},
}


@app.get("/tickets/{ticket_id}")
def get_ticket(ticket_id: int, upper: bool = False):
    ticket = TICKETS[ticket_id]
    if upper:
        return {**ticket, "text": ticket["text"].upper()}
    return ticket

{ticket_id} in the path is a path parameter: whatever sits in that part of the URL is passed to the function argument with the same name. ticket_id: int tells FastAPI to convert it to an int.

upper: bool = False is not in the path, so FastAPI reads it from the query string, as a query parameter. The default makes it optional.

Example
from fastapi.testclient import TestClient
from tickets import app

client = TestClient(app)
print(client.get("/tickets/2").json())
print(client.get("/tickets/2?upper=true").json())

{**ticket, "text": ...} copies the ticket's keys into a new dictionary and replaces text. The stored ticket stays as it was.

A value that is not an int

Example
response = client.get("/tickets/two")
print(response.status_code)
print(response.json())

Your function never ran. FastAPI checked two against the type hint, refused it with 422, and said where: loc is the location, the path parameter ticket_id. It is the same Pydantic error from the Python course, sent as JSON.

A value that is an int but not a ticket

Example
response = client.get("/tickets/9")

9 passes the type check, and TICKETS[9] raises a KeyError inside your function. TestClient hands the app's own exception back to you, so a test sees the real cause; a real server would answer 500. The right answer is 404, which lesson 7 sends.

Try it yourself
  • Add a query parameter field: str | None = None that returns only that field when given.
  • Call /tickets/2?upper=yes, then ?upper=maybe. Which does FastAPI accept?
  • Add a third ticket to TICKETS and fetch it.

Every expert started right here.