
FastAPI
Query parameters can have default values, making them optional. If not provided in the URL, the default is used.
A default value is used when a query parameter is not included in the request URL.
@app.get("/items")
async def list_items(skip: int = 0, limit: int = 10):
# If skip not provided → skip = 0
# If limit not provided → limit = 10
return {"skip": skip, "limit": limit}@app.get("/items")
async def list_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}Different Requests:
1. `/items`
- Response: `{"skip": 0, "limit": 10}`
2. `/items?skip=5`
- Response: `{"skip": 5, "limit": 10}`
3. `/items?limit=20`
- Response: `{"skip": 0, "limit": 20}`
4. `/items?skip=5&limit=20`
- Response: `{"skip": 5, "limit": 20}`
Add `Optional` when you want a parameter that might not be provided:
from typing import Optional
@app.get("/search")
async def search(q: Optional[str] = None):
# q is optional (might be None)
if q:
return {"query": q}
else:
return {"message": "No search query provided"}Requests:
@app.get("/api/items")
async def list_items(
page: int = 1, # Default: 1
per_page: int = 20, # Default: 20
sort: str = "name", # Default: "name"
order: str = "asc", # Default: "asc"
active: bool = True # Default: True
):
return {
"page": page,
"per_page": per_page,
"sort": sort,
"order": order,
"active": active
}Possible Calls:
@app.get("/posts")
async def list_posts(
page: int = 1,
per_page: int = 10
):
skip = (page - 1) * per_page
posts = db.get_posts(skip=skip, limit=per_page)
return {"page": page, "per_page": per_page, "posts": posts}@app.get("/users")
async def list_users(
status: str = "active",
role: Optional[str] = None
):
users = db.list_users(status=status, role=role)
return {"users": users}@app.get("/products")
async def list_products(
sort_by: str = "name",
order: str = "asc"
):
# sort_by could be: "name", "price", "rating"
# order could be: "asc", "desc"
products = db.list_products(sort_by=sort_by, order=order)
return {"products": products}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