typestar

Path and query parameters in Python

Annotations declare where a value comes from and what type it must be.

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


@app.get("/tours/{lang}/{idx}")
def step(lang: str, idx: int, verbose: bool = False):
    body = {"lang": lang, "idx": idx}
    if verbose:
        body["detail"] = "the long version"
    return body


client = TestClient(app)
print(client.get("/tours/rust/3").json())
print(client.get("/tours/rust/3", params={"verbose": True}).json())
print(client.get("/tours/rust/not-a-number").status_code)

How it works

  1. A name in the path is a path parameter, typed by its annotation.
  2. Anything else with a default is a query parameter.
  3. A bad type is a 422 before the handler runs.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
463
Tokens
133
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 2 of 4 in FastAPI routes, step 7 of 19 in Web services & data access.

← Previous Next →