Python / FastAPI Basics Interview Questions
How do you add validation constraints to path and query parameters using Path() and Query()?
FastAPI provides Path() and Query() functions (imported from fastapi) to add metadata and validation constraints to individual parameters — the same constraints available in Pydantic's Field().
from fastapi import FastAPI, Path, Query from typing import Annotated app = FastAPI() @app.get("/items/{item_id}") def read_item( item_id: Annotated[int, Path( title="The ID of the item", description="Must be a positive integer", ge=1, # >= 1 le=1_000_000, # <= 1,000,000 )], q: Annotated[str | None, Query( min_length=3, max_length=50, pattern=r"^[a-z]+$", alias="search", # URL uses ?search=... instead of ?q=... deprecated=True, # marks param as deprecated in docs )] = None, ): return {"item_id": item_id, "q": q} # Required query param with no default @app.get("/search") def search( q: Annotated[str, Query(min_length=1)], # required â no default ): return {"query": q}
The Annotated pattern (Python 3.9+) is FastAPI's recommended way to attach metadata. It keeps the type hint clean while allowing rich validation: Annotated[int, Path(ge=1)] means "an int, validated by Path with ge=1".
More Related questions...