Optional query parameters let users send extra information in a web request, but they don't have to. This makes your app flexible and user-friendly.
Optional query parameters in FastAPI
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/items/") async def read_items(q: Optional[str] = None): if q: return {"query": q} return {"query": "No query provided"}
Use Optional[type] from typing to mark a query parameter as optional.
Set the default value to None to make the parameter optional.
q. If not given, it returns a default message.from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/search/") async def search_items(q: Optional[str] = None): return {"search": q or "No search term"}
category is optional and can be skipped. limit has a default value of 10 if not provided.from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/products/") async def get_products(category: Optional[str] = None, limit: int = 10): return {"category": category, "limit": limit}
This FastAPI app defines one endpoint /items/ with an optional query parameter q. If the user sends ?q=apple, it returns a message with the search term. If q is missing, it returns a default message.
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/items/") async def read_items(q: Optional[str] = None): if q: return {"message": f"You searched for: {q}"} return {"message": "No search query provided"}
Optional query parameters help keep your API flexible and easy to use.
Always set a default value (usually None) to make a parameter optional.
FastAPI automatically documents optional parameters in the API docs.
Optional query parameters let users send extra info but don't have to.
Use Optional[type] and default None to make parameters optional.
This makes your API flexible and user-friendly.
Practice
Solution
Step 1: Understand optional parameters in APIs
Optional means the user does not have to provide the parameter for the request to work.Step 2: Apply to FastAPI query parameters
FastAPI allows parameters to be optional by giving them a default value like None.Final Answer:
The user can choose to include it or not in the request -> Option CQuick Check:
Optional query parameter = user choice [OK]
- Thinking optional means parameter is always required
- Confusing optional with ignored parameters
- Assuming optional means empty string is required
q of type str in FastAPI?Solution
Step 1: Recall syntax for optional query parameters
FastAPI uses Optional[type] with a default value None to mark parameters optional.Step 2: Check each option
def read_items(q: Optional[str] = None): uses Optional[str] and default None, which is correct syntax.Final Answer:
def read_items(q: Optional[str] = None): -> Option AQuick Check:
Optional[str] + = None = correct syntax [OK]
- Omitting the default None value
- Using Optional without import
- Setting type to str without Optional
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"}What will be the JSON response when the client calls
/items/ without any query parameters?Solution
Step 1: Understand default value of q
q is Optional[str] with default None, so if missing, q is None.Step 2: Check the if condition
If q is None (falsey), the function returns {"query": "No query"}.Final Answer:
{"query": "No query"} -> Option BQuick Check:
Missing q returns "No query" [OK]
- Expecting error when param is missing
- Assuming null is returned instead of string
- Confusing empty string with None
q optional:from fastapi import FastAPI
app = FastAPI()
@app.get("/search/")
def search(q: str = None):
return {"q": q}Solution
Step 1: Check parameter typing and default
q has type str but default None, which conflicts because None is not str.Step 2: Correct typing for optional parameter
Use Optional[str] from typing to allow None as a valid default.Final Answer:
q should be typed as Optional[str] when default is None -> Option AQuick Check:
Type must match default None with Optional[str] [OK]
- Not importing Optional but using it
- Making function async unnecessarily
- Using None default without Optional type
page with a default of 1, but if the user sends page=0, it should return an error. How would you declare page to achieve this behavior?Solution
Step 1: Understand default and validation needs
Default 1 means page is not optional, but user can omit it to get 1.Step 2: Handle invalid value 0
Use int with default 1, then inside function check if page == 0 and raise error.Final Answer:
page: int = 1 and check inside function if page == 0 to raise error -> Option DQuick Check:
Default + validation inside function = page: int = 1 and check inside function if page == 0 to raise error [OK]
- Making page Optional[int] = 1 (invalid syntax)
- Not validating 0 value inside function
- Requiring page without default when default needed
Ready to prove it?
Pass the test and this pattern moves unknown
