
FastAPI
Learn the fundamentals of required queries in FastAPI.
Required query parameters must be provided in the request URL, otherwise the API returns a 422 validation error. They don't have default values.
In this section, you'll understand:
from fastapi import FastAPI
app = FastAPI()
# Query parameter with NO default = REQUIRED
@app.get("/search")
async def search(q: str):
# q is REQUIRED
# GET /search ❌ 422 Error
# GET /search?q=python ✅ Valid
return {"query": q}
# Multiple required parameters
@app.get("/convert")
async def convert(value: float, from_unit: str, to_unit: str):
# All three parameters are REQUIRED
return {
"value": value,
"from": from_unit,
"to": to_unit
}To make a parameter optional, add a default value:
from typing import Optional
# Required: no default
@app.get("/items")
async def get_items(category: str):
# category is REQUIRED
return {"category": category}
# Optional: has default
@app.get("/items")
async def get_items(category: str = "all"):
# category is optional, defaults to "all"
return {"category": category}
# Optional: can be None
@app.get("/items")
async def get_items(category: Optional[str] = None):
# category is optional, can be None
return {"category": category}Required parameters are used for:
Ready to explore more? Check out the advanced section for production patterns and edge cases.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward