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.
Practice
Query() in FastAPI for query parameters?Solution
Step 1: Understand the role of
Query()Query()is used in FastAPI to add validation rules to query parameters, such as minimum length or value ranges.Step 2: Identify what
It does not create endpoints, handle databases, or format responses; it only validates input parameters.Query()does not doFinal Answer:
To validate and enforce rules on query parameter values -> Option AQuick Check:
Query() validates parameters = B [OK]
- Thinking Query() creates API routes
- Confusing Query() with response formatting
- Assuming Query() manages database connections
q with a minimum length of 3 in FastAPI?Solution
Step 1: Recall FastAPI query parameter syntax
In FastAPI, you declare a query parameter with its type and assign it to Query() with validation rules, e.g.,q: str = Query(min_length=3).Step 2: Check each option's syntax correctness
q: str = Query(min_length=3) matches the correct pattern. Options B, C, and D misuse type annotations or function calls.Final Answer:
q: str = Query(min_length=3) -> Option DQuick Check:
Correct syntax = A [OK]
- Swapping type and Query() order
- Calling Query() incorrectly as a function
- Missing type annotation before Query()
age is set to 15?from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(age: int = Query(..., ge=18)):
return {"age": age}Solution
Step 1: Understand the validation rule
The query parameteragerequires a value greater or equal to 18 (ge=18).Step 2: Check the input value against the rule
Input age=15 is less than 18, so FastAPI will reject it with a 422 validation error.Final Answer:
422 Unprocessable Entity error -> Option BQuick Check:
age < 18 triggers 422 error = C [OK]
- Assuming invalid input returns null or default
- Expecting server error instead of validation error
- Ignoring validation and returning input as is
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/search/")
async def search_items(q: str = Query(min_length=5)):
return {"query": q}Solution
Step 1: Check if query parameter is required
Query(min_length=5)implicitly sets default=Ellipsis, makingqrequired with string length validation.Step 2: Understand FastAPI requirement for required params
Explicit...is not needed; the code correctly validates required query parameters. No error.Final Answer:
There is no error; the code correctly requires the query parameter with min_length validation -> Option AQuick Check:
Required param needs Query(...) = A [OK]
- Thinking Query(min_length=5) makes param optional
- Confusing min_length with max_length
- Thinking async is invalid for FastAPI endpoints
tags which must be a list of strings, each at least 2 characters long. Which is the correct way to validate this?Solution
Step 1: Understand FastAPI's Query validation limits
FastAPI'sQuery()supportsmin_itemsfor lists butmin_lengthapplies to strings, not list elements.Step 2: Validate list and individual string lengths
To ensure each string in the list is at least 2 characters, you must add custom validation logic beyondQuery().Final Answer:
tags: list[str] = Query(..., min_items=1), with custom validation for string length -> Option CQuick Check:
List length via Query, element length via custom code = D [OK]
- Using min_length on list instead of strings inside
- Not validating individual string lengths
- Declaring tags as a single string instead of list
Ready to prove it?
Pass the test and this pattern moves unknown
