FastAPI Cheatsheet

Path and Query Parameters

Use this FastAPI reference while you build software engineering projects, review code, or refresh the syntax you reach for most.

Path Parameters

from fastapi import FastAPI, Path

app = FastAPI()

# Basic — type inferred from annotation
@app.get("/items/{item_id}")
def get_item(item_id: int):
    return {"id": item_id}

# With validation via Path()
@app.get("/items/{item_id}")
def get_item(
    item_id: int = Path(
        ...,              # required (same as ...)
        title="Item ID",
        description="Must be >= 1",
        ge=1,
        le=1000,
    )
):
    return {"id": item_id}

Query Parameters

from fastapi import Query

# Simple — any param NOT in the path string is a query param
@app.get("/items")
def list_items(skip: int = 0, limit: int = 10):
    return db[skip : skip + limit]

# Optional query param
from typing import Optional

@app.get("/items")
def list_items(q: Optional[str] = None):
    return {"q": q}

# With Query() metadata + validation
@app.get("/search")
def search(
    q: str = Query(
        default=...,          # required; use None for optional
        min_length=3,
        max_length=50,
        pattern=r"^\w+$",
        alias="query",        # URL uses ?query= but Python sees `q`
        title="Search term",
        description="Search the catalog",
        deprecated=False,
        include_in_schema=True,
    )
):
    return {"q": q}

Multi-Value Query Parameters (list)

from typing import List

@app.get("/items")
def list_items(tags: List[str] = Query(default=[])):
    # URL: /items?tags=a&tags=b&tags=c
    return {"tags": tags}

Parameter Comparison Table

ClassWhere declaredTypical use
Path(...)URL path segment {name}resource IDs
Query(...)?key=value in URLfilters, pagination
Header(...)HTTP request headerstokens, content-type
Cookie(...)HTTP cookiessession, tracking
Body(...)request body fieldcomplex objects
Form(...)application/x-www-form-urlencodedHTML forms
File(...)multipart/form-datafile uploads

Header Parameters

from fastapi import Header

@app.get("/items")
def get_items(user_agent: str = Header(default=None)):
    return {"User-Agent": user_agent}

# FastAPI auto-converts hyphens → underscores:
# X-Token header → x_token parameter
@app.get("/secure")
def secure(x_token: str = Header(...)):
    return {"token": x_token}

# Disable conversion:
@app.get("/raw")
def raw(accept_encoding: str = Header(default=None, convert_underscores=False)):
    ...

Path + Query Together

@app.get("/users/{user_id}/items")
def user_items(
    user_id: int = Path(..., ge=1),
    skip: int = Query(default=0, ge=0),
    limit: int = Query(default=10, le=100),
    q: Optional[str] = None,
):
    return {"user": user_id, "skip": skip, "limit": limit, "q": q}

Validation Options for Path / Query

OptionTypeNotes
min_lengthintstring min length
max_lengthintstring max length
patternstrregex; replaces old regex=
gtfloatgreater than
gefloatgreater than or equal
ltfloatless than
lefloatless than or equal
multiple_offloatmust be a multiple
aliasstralternate URL name
titlestrOpenAPI docs label
descriptionstrOpenAPI docs text
deprecatedboolmark in docs
include_in_schemaboolhide from OpenAPI
exampleAnysingle doc example
examplesdictnamed examples (OpenAPI 3.1)

Enum Path Parameters

from enum import Enum

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

@app.get("/models/{model_name}")
def get_model(model_name: ModelName):
    if model_name is ModelName.alexnet:
        return {"model": model_name, "message": "Deep Learning FTW!"}
    return {"model": model_name}

File Path Parameter (catch-all)

# matches /files/home/user/report.pdf
@app.get("/files/{file_path:path}")
def read_file(file_path: str):
    return {"path": file_path}

Numeric Type Shorthand

# int, float, Decimal all work; FastAPI coerces from string
@app.get("/calc")
def calc(x: float = 0.0, n: int = 1):
    return x ** n

Boolean Query Parameters

# Truthy: 1, true, on, yes  |  Falsy: 0, false, off, no  (case-insensitive)
@app.get("/items")
def list_items(active: bool = True):
    return {"active": active}