Query parameter validation helps check user inputs in the URL to keep your app safe and working well.
Query parameter validation in FastAPI
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: str = Query(..., min_length=3, max_length=10)): return {"q": q}
Use Query() to add validation rules to query parameters.
The ... means the parameter is required.
q with length limits.from fastapi import FastAPI, Query app = FastAPI() @app.get("/search/") async def search_items(q: str = Query(None, min_length=3, max_length=20)): return {"query": q}
num between 1 and 100.from fastapi import FastAPI, Query app = FastAPI() @app.get("/numbers/") async def get_numbers(num: int = Query(..., ge=1, le=100)): return {"number": num}
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: str = Query("default", min_length=2)): return {"q": q}
This FastAPI app has a route /products/ that requires a category query parameter with length between 3 and 15 characters. It also has an optional limit parameter that must be between 1 and 50, defaulting to 10.
from fastapi import FastAPI, Query app = FastAPI() @app.get("/products/") async def get_products( category: str = Query(..., min_length=3, max_length=15), limit: int = Query(10, ge=1, le=50) ): return {"category": category, "limit": limit}
Validation errors automatically return clear messages to the user.
You can combine many validation rules like min_length, max_length, ge (greater or equal), and le (less or equal).
Use Query(...) to make a parameter required, or Query(default_value) to make it optional.
Query parameter validation checks user inputs in the URL to keep your app safe and correct.
FastAPI uses Query() to add rules like length or number ranges.
Validation helps give clear errors and avoid bad data in your app.