How to Use Optional Parameters in FastAPI: Simple Guide
In FastAPI, you make a parameter optional by giving it a default value, usually
None. You can do this by typing the parameter as Optional[type] and assigning None as the default, so FastAPI knows it can be omitted in requests.Syntax
To declare an optional parameter in FastAPI, you use Python's Optional type hint from the typing module and assign a default value, typically None. This tells FastAPI the parameter is not required.
Example parts explained:
param: Optional[str] = None:paramis a string that can be missing.Optional[str]: means the parameter can be a string orNone.= None: sets the default value, making it optional.
python
from typing import Optional from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: Optional[str] = None): if q: return {"query": q} return {"query": "No query provided"}
Example
This example shows a FastAPI endpoint with an optional query parameter q. If the client sends q, the response includes it; otherwise, it returns a default message.
python
from typing import Optional from fastapi import FastAPI app = FastAPI() @app.get("/search/") async def search(q: Optional[str] = None): if q: return {"result": f"You searched for: {q}"} return {"result": "No search query provided"}
Output
GET /search/?q=fastapi -> {"result": "You searched for: fastapi"}
GET /search/ -> {"result": "No search query provided"}
Common Pitfalls
Common mistakes when using optional parameters in FastAPI include:
- Not assigning a default value, which makes the parameter required.
- Using
Optionalwithout a default value, which does not make the parameter optional. - Confusing path parameters with query parameters; path parameters cannot be optional.
Correct usage requires both Optional[type] and a default value like = None.
python
from typing import Optional from fastapi import FastAPI app = FastAPI() # Wrong: Optional without default - still required @app.get("/wrong1/") async def wrong1(q: Optional[str]): return {"q": q} # Right: Optional with default None - optional @app.get("/right1/") async def right1(q: Optional[str] = None): return {"q": q}
Quick Reference
Summary tips for optional parameters in FastAPI:
- Use
Optional[type]fromtypingto indicate the parameter can be missing. - Always assign a default value like
= Noneto make it optional. - Optional parameters are usually query parameters, not path parameters.
- Check if the parameter is
Noneinside your function to handle missing values.
Key Takeaways
Make parameters optional by typing them as Optional and assigning a default value None.
Optional parameters in FastAPI are usually query parameters, not path parameters.
Always assign a default value to avoid making the parameter required.
Check for None inside your endpoint to handle missing optional parameters gracefully.