Python / FastAPI 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".
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
