Sometimes you want to get several pieces of information from a user in a web request. Multiple query parameters let you do that easily.
Multiple query parameters in FastAPI
from fastapi import FastAPI from typing import List, Optional app = FastAPI() @app.get("/items/") async def read_items( q: Optional[str] = None, # single optional query tags: Optional[List[str]] = None # multiple values for same key ): return {"q": q, "tags": tags}
Use Python type hints to declare query parameters.
Optional parameters can have a default value like None.
q is required, page is optional with default 1.from fastapi import FastAPI app = FastAPI() @app.get("/search/") async def search(q: str, page: int = 1): return {"query": q, "page": page}
tags query parameters like ?tags=red&tags=blue.from fastapi import FastAPI from typing import List, Optional app = FastAPI() @app.get("/filter/") async def filter_items(tags: Optional[List[str]] = None): return {"tags": tags}
This FastAPI app defines a route /products/ that accepts multiple query parameters: category, price_min, price_max, and multiple tags. All are optional. You can call it like /products/?category=books&price_min=10&tags=fiction&tags=bestseller.
from fastapi import FastAPI from typing import List, Optional app = FastAPI() @app.get("/products/") async def get_products( category: Optional[str] = None, price_min: Optional[float] = None, price_max: Optional[float] = None, tags: Optional[List[str]] = None ): return { "category": category, "price_min": price_min, "price_max": price_max, "tags": tags }
Query parameters are always strings in URLs but FastAPI converts them to the types you specify.
Use Optional to make parameters not required.
For multiple values with the same key, use a list type like List[str].
Multiple query parameters let you get many inputs from a URL.
Use Python types and Optional to control required or optional parameters.
Use List types to accept multiple values for the same query key.
Practice
Solution
Step 1: Understand query parameters in FastAPI
Query parameters allow passing data in the URL after a question mark, like ?name=John.Step 2: Purpose of multiple query parameters
Using multiple query parameters lets the API accept many inputs to customize what it returns.Final Answer:
To accept several inputs from the URL to customize the response -> Option AQuick Check:
Multiple query parameters = multiple inputs [OK]
- Confusing query parameters with request body
- Thinking multiple query parameters define routes
- Assuming query parameters only work with POST
name (string) and age (integer) in a FastAPI path operation function?Solution
Step 1: Understand FastAPI query parameter declaration
UsingQuery(...)marks parameters as required query parameters with type hints.Step 2: Check parameter types and usage
Parameters must have correct types and useQuery(...)to be recognized as query parameters.Final Answer:
def read_user(name: str = Query(...), age: int = Query(...)): -> Option AQuick Check:
Use Query(...) with correct types for query parameters [OK]
- Swapping types of parameters
- Not using Query for required parameters
- Omitting type hints
from fastapi import FastAPI, Query
from typing import List
app = FastAPI()
@app.get('/items/')
async def read_items(q: List[str] = Query([])):
return {"q": q}What will be the output if the URL is
/items/?q=apple&q=banana?Solution
Step 1: Understand List query parameters in FastAPI
UsingList[str]withQuery([])allows multiple values for the same query key to be collected into a list.Step 2: Analyze the URL query parameters
The URL hasq=appleandq=banana, so FastAPI collects both into a list.Final Answer:
{"q": ["apple", "banana"]} -> Option CQuick Check:
Multiple query keys = list of values [OK]
- Expecting a single string with commas
- Getting only the first value
- Getting an empty list
name and age?:from fastapi import FastAPI
app = FastAPI()
@app.get('/user/')
def get_user(name: str, age: int = None):
return {"name": name, "age": age}Solution
Step 1: Check optional query parameter typing
In FastAPI, optional parameters should useOptional[type]ortype | Noneto mark them optional properly.Step 2: Analyze
Just setting default to None is not enough; the type hint should beage: int = NoneOptional[int]orint | Nonefor FastAPI to treat it as optional.Final Answer:
The parameter age should use Optional[int] for optional query -> Option DQuick Check:
Optional query params need Optional[type] or type | None [OK]
- Assuming default None alone makes param optional
- Forgetting to import Optional
- Thinking async is required for all endpoints
tags (list of strings), limit (integer, default 10), and search (optional string). Which of the following function signatures correctly implements this?Solution
Step 1: Use Query() for query parameters with defaults
FastAPI requires usingQuery()to specify default values and metadata for query parameters.Step 2: Correctly type optional parameters
UseOptional[str]orstr | NonewithQuery(None)for optional string parameters.Step 3: Check all parameters in def get_items(tags: List[str] = Query([]), limit: int = Query(10), search: Optional[str] = Query(None)):
def get_items(tags: List[str] = Query([]), limit: int = Query(10), search: Optional[str] = Query(None)): usesQuery([])for list default,Query(10)for limit default, andOptional[str] = Query(None)for optional search, which is correct.Final Answer:
def get_items(tags: List[str] = Query([]), limit: int = Query(10), search: Optional[str] = Query(None)): -> Option BQuick Check:
Use Query() with correct types and defaults for multiple optional queries [OK]
- Using mutable default [] without Query()
- Not marking optional string with Optional
- Omitting Query() for default values
Ready to prove it?
Pass the test and this pattern moves unknown
