How to Use Query Parameters in FastAPI: Simple Guide
In FastAPI, you use query parameters by adding function parameters with default values or type annotations in your path operation function. FastAPI automatically reads these parameters from the URL query string using
def function arguments.Syntax
To use query parameters in FastAPI, define them as function parameters in your path operation function. If you give a parameter a default value, FastAPI treats it as a query parameter.
param: type = defaultmeansparamis a query parameter of the giventype.- If no default is given, the parameter is required.
- FastAPI extracts the value from the URL query string automatically.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str = None, limit: int = 10): return {"q": q, "limit": limit}
Example
This example shows a FastAPI app with two query parameters: q (optional string) and limit (integer with default 10). When you visit /items/?q=apple&limit=5, FastAPI reads these values and returns them in JSON.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str = None, limit: int = 10): return {"q": q, "limit": limit}
Output
{"q": "apple", "limit": 5}
Common Pitfalls
Common mistakes when using query parameters in FastAPI include:
- Not providing a default value makes the parameter required, which can cause errors if missing.
- Using path parameters and query parameters with the same name causes conflicts.
- Forgetting to use the correct type annotation can lead to unexpected type errors.
Always give a default value for optional query parameters and use distinct names for path and query parameters.
python
from fastapi import FastAPI app = FastAPI() # Wrong: missing default makes q required @app.get("/items/") async def read_items_wrong(q: str): return {"q": q} # Right: q is optional with default None @app.get("/items/") async def read_items_right(q: str = None): return {"q": q}
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Define query parameter | def func(param: type = default) | Default value makes it optional |
| Required query parameter | def func(param: type) | No default means required |
| Multiple query parameters | def func(p1: type1 = default1, p2: type2 = default2) | Each is read from URL query string |
| Type conversion | Use Python types (int, float, bool, str) | FastAPI converts automatically |
| Avoid name conflicts | Use unique names for path and query params | Prevents routing errors |
Key Takeaways
Define query parameters as function arguments with default values in FastAPI.
Parameters without defaults are required query parameters.
FastAPI automatically converts query parameters to the declared Python types.
Avoid using the same name for path and query parameters to prevent conflicts.
Optional query parameters should have a default value like None.