How to Use Default Value for Parameter in FastAPI
In FastAPI, you set a default value for a parameter by assigning it directly in the function signature using
=. This makes the parameter optional, and if the client does not provide it, FastAPI uses the default value automatically.Syntax
To use a default value for a parameter in FastAPI, define the parameter with an assignment in the function signature. This works for query parameters, path parameters (with some restrictions), and request body fields.
param: type = default_valuemeansparamis optional.- If the client omits
param, FastAPI usesdefault_value. - If the client provides
param, FastAPI uses the provided value.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str = "default"): return {"q": q}
Example
This example shows a GET endpoint with a query parameter q that has a default value of "default". If you call the endpoint without q, it returns the default. If you provide q, it returns your value.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str = "default"): return {"q": q} # Run with: uvicorn filename:app --reload # Example requests: # GET /items/ -> {"q": "default"} # GET /items/?q=hello -> {"q": "hello"}
Output
{"q": "default"} (when no query parameter is given)
{"q": "hello"} (when ?q=hello is provided)
Common Pitfalls
Some common mistakes when using default values in FastAPI include:
- Forgetting to assign a default value, which makes the parameter required.
- Using default values on path parameters, which is not supported because path parameters must always be provided.
- Confusing query parameters with request body parameters; default values work differently for body fields.
Always assign default values only to query or optional parameters.
python
from fastapi import FastAPI app = FastAPI() # Wrong: path parameter cannot have default # @app.get("/items/{item_id}") # async def read_item(item_id: int = 10): # return {"item_id": item_id} # Right: path parameter without default @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} # Query parameter with default @app.get("/search/") async def search(q: str = "all"): return {"q": q}
Quick Reference
Tips for using default values in FastAPI parameters:
- Use
param: type = defaultfor optional query parameters. - Path parameters must not have default values.
- Default values make parameters optional in the API.
- Use
Noneas a default to make parameters optional and check forNoneinside the function.
Key Takeaways
Assign default values in function parameters to make FastAPI parameters optional.
Default values work for query parameters but not for path parameters.
If a client omits an optional parameter, FastAPI uses the default value automatically.
Use None as a default to detect if a parameter was provided or not.
Always test your endpoints to confirm default values behave as expected.