Path parameters are variable parts of the URL path, declared with curly braces and received as function arguments. FastAPI converts and validates them using the declared type hints.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
GET /items/5 → {"item_id": 5} (converted to int).GET /items/foo → automatic error 422 Unprocessable Entity with a clear message, no manual parsing needed.@app.get("/users/me")
def read_current_user():
return {"user_id": "the current user"}
@app.get("/users/{user_id}")
def read_user(user_id: str):
return {"user_id": user_id}
Routes are evaluated in declaration order. /users/me must be declared before /users/{user_id}, otherwise "me" would be captured as a user_id.
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_name": model_name, "message": "Deep Learning FTW!"}
return {"model_name": model_name, "message": "Have some residuals"}
Only the values alexnet, resnet, lenet are accepted; anything else returns 422 with the list of valid options.
from fastapi import FastAPI, Path
@app.get("/items/{item_id}")
def read_item(item_id: int = Path(title="The ID of the item", ge=1, le=1000)):
return {"item_id": item_id}
ge=1 (greater than or equal) rejects IDs like 0 or negatives; the title appears in the OpenAPI docs.
@app.get("/files/{file_path:path}")
def read_file(file_path: str):
return {"file_path": file_path}
By default a parameter cannot contain slashes. The :path converter captures multi-segment paths like /files/home/user/report.pdf.
A: 422 Unprocessable Entity with a JSON body listing the exact location, message and type of each validation error, e.g. {"loc": ["path", "item_id"], "msg": "value is not a valid integer"}.
A: No. Path parameters are always required because they are part of the URL structure; if you give a default, FastAPI raises an error. Only query parameters can be optional.
A: FastAPI resolves parameters by name in this order: path parameters first (by matching the route), then query parameters. Use Path() or Query() to be explicit when the same name appears in more than one place.
Path parameters let one route serve many resources. Type hints turn them into validated, documented values for free: declare int, UUID, Enum or add constraints with Path(ge=..., le=...) and FastAPI handles conversion, errors and docs.