Query parameters let users ask for specific data by adding extra details to a web address. This helps show only the data they want, making responses faster and clearer.
Why query parameters filter data 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 {"filtered_query": q} return {"message": "No filter applied"}
Query parameters are defined as function parameters with default values.
Optional parameters mean the user can choose to add them or not.
keyword that filters search results.from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/search/") async def search_items(keyword: Optional[str] = None): if keyword: return {"search": keyword} return {"search": "all items"}
category to filter products and limit to control how many products to show.from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/products/") async def list_products(category: Optional[str] = None, limit: int = 10): return {"category": category, "limit": limit}
This FastAPI app returns all items by default. If you add a query parameter like ?category=fruit, it returns only items in that category.
from fastapi import FastAPI from typing import Optional app = FastAPI() items = [ {"id": 1, "name": "apple", "category": "fruit"}, {"id": 2, "name": "carrot", "category": "vegetable"}, {"id": 3, "name": "banana", "category": "fruit"} ] @app.get("/items/") async def get_items(category: Optional[str] = None): if category: filtered = [item for item in items if item["category"] == category] return {"filtered_items": filtered} return {"all_items": items}
Query parameters are always optional unless you make them required by removing the default value.
They help keep URLs clean and APIs flexible.
Use typing.Optional to indicate parameters that may or may not be provided.
Query parameters let users filter or customize data returned by an API.
They are added to the URL after a question mark and are easy to define in FastAPI functions.
Using query parameters makes your API more useful and efficient.
Practice
Solution
Step 1: Understand what query parameters do
Query parameters are used to send extra information in the URL to control what data the API returns.Step 2: Identify the purpose in FastAPI
In FastAPI, query parameters let users filter or customize the response without changing the endpoint itself.Final Answer:
To filter or customize the data returned by the API -> Option AQuick Check:
Query parameters = filter/customize data [OK]
- Confusing query parameters with HTTP methods
- Thinking query parameters set server or database settings
- Assuming query parameters change endpoint URLs
category in FastAPI?Solution
Step 1: Recall how to declare optional query parameters
In FastAPI, optional query parameters are declared by giving a default value, often None.Step 2: Check the options for correct syntax
def read_items(category: str = None): usescategory: str = None, which means the parameter is optional and of type string.Final Answer:
def read_items(category: str = None): -> Option BQuick Check:
Optional query param = default None [OK]
- Not providing a default value for optional parameters
- Using wrong data types for query parameters
- Omitting type annotations
from fastapi import FastAPI
app = FastAPI()
items = [
{"name": "apple", "category": "fruit"},
{"name": "carrot", "category": "vegetable"}
]
@app.get("/items")
async def read_items(category: str = None):
if category:
return [item for item in items if item["category"] == category]
return itemsWhat will be the output of a GET request to
/items?category=fruit?Solution
Step 1: Understand the query parameter usage
The endpoint checks ifcategoryis given, then filters items matching that category.Step 2: Apply the filter for category='fruit'
Only the item with category 'fruit' is the apple, so the returned list contains only that item.Final Answer:
[{"name": "apple", "category": "fruit"}] -> Option AQuick Check:
Filter by category 'fruit' returns apple [OK]
- Returning all items ignoring the filter
- Returning empty list when filter matches
- Confusing category values
color:from fastapi import FastAPI
app = FastAPI()
items = [
{"name": "shirt", "color": "blue"},
{"name": "pants", "color": "black"}
]
@app.get("/items")
def read_items(color):
return [item for item in items if item["color"] == color]Solution
Step 1: Check function parameter declaration
The parameter 'color' lacks a type annotation and default value, so FastAPI treats it as a required path parameter, causing errors.Step 2: Correct declaration for query parameter
Adding a type (e.g., str) and a default (e.g., None) makes it an optional query parameter, fixing the error.Final Answer:
The query parameter 'color' is missing a type annotation and default value -> Option DQuick Check:
Query params need type and default [OK]
- Omitting type annotations for query parameters
- Confusing query parameters with path parameters
- Using wrong HTTP methods for filtering
category and max_price. Which code snippet correctly implements this filtering?Solution
Step 1: Understand optional query parameters usage
Bothcategoryandmax_priceare optional, so they need default values (None) to allow filtering only when provided.Step 2: Check filtering logic
async def get_products(category: str = None, max_price: float = None): filtered = products if category: filtered = [p for p in filtered if p['category'] == category] if max_price is not None: filtered = [p for p in filtered if p['price'] <= max_price] return filtered filters products step-by-step, applying each filter only if the parameter is given, which is correct and safe.Final Answer:
async def get_products(category: str = None, max_price: float = None): filtered = products if category: filtered = [p for p in filtered if p['category'] == category] if max_price is not None: filtered = [p for p in filtered if p['price'] <= max_price] return filtered -> Option CQuick Check:
Optional filters with defaults and conditions = correct [OK]
- Not providing default values for optional parameters
- Filtering without checking if parameters exist
- Returning unfiltered data ignoring query parameters
Ready to prove it?
Pass the test and this pattern moves unknown
