Query-Parameter-Validation
Query Parameter Validations
What is Validation in Query parameter
In FastAPI, validation in query parameters refers to the automatic checking and enforcement of rules on the values passed through the URL's query string. FastAPI uses Pydantic and type hints to perform this validation.
How Validation Works
FastAPI validates query parameters using:
- Type annotations (e.g.,
int,str,bool) - Default values
- Pydantic's Query() function for more advanced validation
Example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
If a user passes ?skip=abc, FastAPI will return a 422 Unprocessable Entity error because abc is not an integer.
Advanced Validation with Query
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
def read_items(
q: str = Query(..., min_length=3, max_length=50, regex="^item")
):
return {"q": q}
``
Here are several common and practical examples of using query parameter validation in FastAPI, ranging from basic to more advanced use cases:
Common Examples
1. Basic Type Validation
from fastapi import FastAPI
app = FastAPI()
@app.get("/products/")
def get_products(page: int = 1, size: int = 10):
return {"page": page, "size": size}
- Validates that
pageandsizeare integers. - Returns a 422 error if someone sends
?page=abc.
2. String Length and Pattern Validation
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/search/")
def search_items(
keyword: str = Query(..., min_length=3, max_length=50, regex="^[a-zA-Z0-9 ]+$")
):
return {"keyword": keyword}
...makeskeywordrequired- Enforces:
- Minimum length: 3
- Maximum length: 50
- Only alphanumeric characters and spaces
3. Optional Parameters with Default Values
@app.get("/filter/")
def filter_items(
category: str = Query(None),
in_stock: bool = Query(False)
):
return {"category": category, "in_stock": in_stock}
categoryis optionalin_stockdefaults toFalse
4. List of Values
@app.get("/tags/")
def get_items_by_tags(tags: list[str] = Query([])):
return {"tags": tags}
- Accepts multiple values like:
/tags/?tags=python&tags=fastapi&tags=api
5. Range Validation for Numbers
@app.get("/ratings/")
def get_ratings(
min_rating: float = Query(0, ge=0, le=5),
max_rating: float = Query(5, ge=0, le=5)
):
return {"min_rating": min_rating, "max_rating": max_rating}
- Ensures ratings are between 0 and 5
ge= greater than or equal,le= less than or equal
6. Using Aliases for Query Parameters
@app.get("/items/")
def get_items(
sort_by: str = Query("name", alias="sortBy")
):
return {"sort_by": sort_by}
- Accepts
?sortBy=pricein the URL, but maps it tosort_byin the function
7. Deprecating a Parameter
@app.get("/legacy/")
def legacy_endpoint(
old_param: str = Query(None, deprecated=True)
):
return {"old_param": old_param}
- Marks
old_paramas deprecated in the OpenAPI docs