Path Parameters
Path parameters are values captured from the URL path itself, like the 42 in /users/42. In FastAPI you declare them in the route string and type them in the function signature; the framework extracts, validates, and converts them for you.
Basic Usage
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
GET /items/42 returns {"item_id": 42}. GET /items/abc returns a 422 validation error explaining that the value is not an integer.
Type Conversion
| Annotation | Accepted | Example |
|---|---|---|
| int | integers only | /items/42 |
| float | integers or decimals | /items/4.5 |
| str | anything | /items/abc |
| bool | true/false variants | /items/true |
Multiple Path Parameters
@app.get("/users/{user_id}/orders/{order_id}")
def read_order(user_id: int, order_id: int):
return {"user_id": user_id, "order_id": order_id}
Constrained Path Parameters
Use Annotated with Pydantic Field to constrain path values, or regex-style validation via query/path classes:
from typing import Annotated
from pydantic import Field
@app.get("/items/{item_id}")
def read_item(item_id: Annotated[int, Field(gt=0)]):
return {"item_id": item_id} # 0 and negatives are rejected
Summary
Declare path parameters as {name} in the route and annotate them in the signature: FastAPI extracts the value, converts it to the declared type, and returns a clear 422 on mismatch. Add Field constraints for ranges and patterns, use multiple {placeholders} for nested resources, and keep the placeholder name identical to the function parameter name so the binding is obvious in the OpenAPI docs.