Beyond type checking, FastAPI lets you add constraints to path/query parameters and model fields using Query, Path, and Field — enforcing rules like length, ranges, and patterns, with automatic 422 errors and documentation when violated.
Beyond type checking, FastAPI lets you add constraints to path/query parameters and model fields using Query, Path, and Field — enforcing rules like length, ranges, and patterns, with automatic 422 errors and documentation when violated.
from fastapi import Query, Path
@app.get("/items")
def search(
q: str = Query(min_length=3, max_length=50), # string length bounds
page: int = Query(default=1, ge=1), # >= 1
limit: int = Query(default=10, ge=1, le=100), # 1 <= limit <= 100
code: str = Query(pattern=r"^[A-Z]{3}$"), # regex pattern
):
...
@app.get("/items/{item_id}")
def get(item_id: int = Path(ge=1)): # path param must be >= 1
...
Query() and Path() add constraints to query and path parameters. Common ones: min_length/max_length (strings), ge/gt/le/lt (numbers), pattern (regex). Violations produce a clear 422 error automatically.
from pydantic import BaseModel, Field, EmailStr
class User(BaseModel):
name: str = Field(min_length=1, max_length=100)
age: int = Field(ge=0, le=120)
email: EmailStr # format validation via a type
bio: str = Field(default="", max_length=500, description="User bio")
The same constraints apply to model fields via Field(), validating request bodies. Specialized types (EmailStr, HttpUrl, UUID) validate formats.
q: str = Query(min_length=3, description="Search query", example="phone")
# the constraints + description + example appear in the auto-generated API docs
Every constraint you declare is also reflected in the OpenAPI documentation, so consumers see the rules.
Adding validation constraints is important for both security/robustness and good API design — declaring rules (length limits, numeric ranges, regex patterns, format types) ensures malformed or malicious input is rejected with clear errors before reaching your logic, which is essential since you must never trust raw input.
FastAPI makes this declarative and effortless: Query/Path/Field constraints are validated automatically (producing structured 422 errors) and simultaneously documented in the API docs, so the rules are enforced and communicated from a single declaration.
Knowing the common constraints and specialized validation types is everyday knowledge for building safe, well-defined endpoints — it's how you go beyond basic type checking to enforce the actual business rules your data must satisfy.