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
| Class | Where declared | Typical use |
|---|---|---|
Path(...) | URL path segment {name} | resource IDs |
Query(...) | ?key=value in URL | filters, pagination |
Header(...) | HTTP request headers | tokens, content-type |
Cookie(...) | HTTP cookies | session, tracking |
Body(...) | request body field | complex objects |
Form(...) | application/x-www-form-urlencoded | HTML forms |
File(...) | multipart/form-data | file 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
| Option | Type | Notes |
|---|---|---|
min_length | int | string min length |
max_length | int | string max length |
pattern | str | regex; replaces old regex= |
gt | float | greater than |
ge | float | greater than or equal |
lt | float | less than |
le | float | less than or equal |
multiple_of | float | must be a multiple |
alias | str | alternate URL name |
title | str | OpenAPI docs label |
description | str | OpenAPI docs text |
deprecated | bool | mark in docs |
include_in_schema | bool | hide from OpenAPI |
example | Any | single doc example |
examples | dict | named 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}