Unvalidated query parameters are a silent API bug: a client sends page=0 or size=10000, the server still answers 200, then quietly returns wrong data or “carries” the whole table. FastAPI solves this with Query() — declare the limits right in the function signature, and the framework checks them and returns a 422 error when a value is wrong, without a single extra if. Use it for every endpoint that takes pagination, search, or filters.
The Problem
A product-listing endpoint with pagination and name search, written without Query(), usually looks like this:
from fastapi import FastAPI
app = FastAPI()
ITEMS = [{"id": i, "name": f"san-pham-{i}"} for i in range(1, 51)]
@app.get("/items/")
def list_items(q: str | None = None, page: int = 1, size: int = 10):
start = (page - 1) * size
return ITEMS[start : start + size]
First, page=0 makes start = -10, and the Python slice [-10:0] returns the last 10 rows of the table — wrong data, but the status is still 200, so the client never knows it got the wrong page. Second, size=10000 forces the server to return the whole table — slow and memory-hungry, and a few requests like that are enough to choke the API. Third, a one-character q still triggers a full-table search whose results are almost meaningless. Patching it with if checks and raise HTTPException at the top of every endpoint just repeats the same code everywhere, and one forgotten spot leaves a hole.
The Solution
Instead of checking by hand, declare the limits right in the function signature:
from fastapi import FastAPI, Query
app = FastAPI()
ITEMS = [{"id": i, "name": f"san-pham-{i}"} for i in range(1, 51)]
@app.get("/items/")
def list_items(
q: str | None = Query(default=None, min_length=2, max_length=50),
page: int = Query(default=1, ge=1),
size: int = Query(default=10, ge=1, le=100),
):
results = ITEMS
if q:
results = [item for item in results if q in item["name"]]
start = (page - 1) * size
return results[start : start + size]
Now a page below 1, a size above 100, or a q shorter than 2 characters is rejected before the function even runs, and FastAPI returns a 422 with a clear message, for example Input should be greater than or equal to 1. The four most-used options: ge/le bound numbers, min_length/max_length bound strings, default sets the value used when the client sends nothing, and pattern matches a regex when needed — for example a product code made of letters and digits only. Note that ge allows exactly the limit while gt does not — so page uses ge=1, not gt=0, because ge states the intent more clearly. If you already have a shared pagination dependency, attach Query() to it once and every endpoint benefits.
Apply It to Your Project
Apply this to every endpoint that takes data from the query string: list pages, search boxes, filters by status or date range. Always set le on size (100 is a good default) so nobody can “ask for” the whole table in one request, and set min_length on search keywords to avoid meaningless queries scanning the entire table. The stricter the validation at the gate, the simpler the code inside.
Related Posts
FastAPI: Handle Heavy Work in the Background with BackgroundTasks — the Client Never Waits
FastAPI: Manage DB Sessions Safely with a Yield Dependency in 5 Minutes
FastAPI: Share One Pagination Dependency Across Every Endpoint — Stop Repeating skip/limit
FAQ
How is Query() different from Pydantic’s Field()?
They share the same constraint system — ge, le, min_length — but Query() is for query parameters in the function signature, while Field() is for fields inside a request-body model.
How do I force the client to send a parameter?
Use Query(...) with an ellipsis instead of a default value — if the parameter is missing, FastAPI returns a 422 right away.
How do I accept several values for one parameter, for example ?tag=a&tag=b?
Declare tags: list[str] = Query(default=[]) and FastAPI collects the repeated values into a list automatically.
What does the 422 error look like, and can I customize it?
FastAPI returns JSON with a detail array, each item naming the error location (loc), the message (msg), and the error type (type). To change the format API-wide, register one exception handler for RequestValidationError on the app.
💬 Have you tried this approach in your own project? If you ran into an error or know a more concise way to do it, leave a comment below — I read every one and will add the best ideas to the post.
References
FastAPI docs — Query Parameters and String Validations: https://fastapi.tiangolo.com/tutorial/query-params-str-validations/
FastAPI docs — Query Parameters: https://fastapi.tiangolo.com/tutorial/query-params/
Top comments (0)