📖 Scenario: You are building a simple web API using FastAPI. Your API will accept multiple query parameters from the URL to filter a list of items.Imagine you have a store with products, and you want users to search products by category and price range using query parameters.
🎯 Goal: Create a FastAPI app that accepts two query parameters: category and max_price. The app should return a filtered list of products matching the category and with price less than or equal to max_price.
📋 What You'll Learn
Create a list of products as dictionaries with keys 'name', 'category', and 'price'.
Add query parameters category (string) and max_price (float) to the GET endpoint.
Filter the products list based on the query parameters.
Return the filtered list as JSON response.
💡 Why This Matters
🌍 Real World
APIs often need to accept multiple query parameters to filter or search data, like searching products by category and price.
💼 Career
Understanding how to handle multiple query parameters in FastAPI is essential for backend web development and building flexible APIs.
Progress0 / 4 steps
1
DATA SETUP: Create the products list
Create a list called products with these exact dictionaries: {'name': 'Apple', 'category': 'fruit', 'price': 1.2}, {'name': 'Banana', 'category': 'fruit', 'price': 0.5}, {'name': 'Carrot', 'category': 'vegetable', 'price': 0.8}, {'name': 'Steak', 'category': 'meat', 'price': 5.0}.
FastAPI
Hint
Use a list of dictionaries exactly as shown.
2
CONFIGURATION: Import FastAPI and create app
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Hint
Use from fastapi import FastAPI and app = FastAPI().
3
CORE LOGIC: Create GET endpoint with query parameters
Create a GET endpoint at /items/ using @app.get("/items/"). Define a function read_items with two query parameters: category: str and max_price: float. Inside the function, filter products to include only items where item['category'] == category and item['price'] <= max_price. Return the filtered list.
FastAPI
Hint
Use a list comprehension to filter products by category and max_price.
4
COMPLETION: Add type hints and async keyword
Ensure the endpoint function read_items is declared with async def and has type hints for category: str and max_price: float. Confirm the function returns the filtered list of products.
FastAPI
Hint
Make sure the function is async and has correct type hints.
Practice
(1/5)
1. What is the main purpose of using multiple query parameters in a FastAPI endpoint?
easy
A. To accept several inputs from the URL to customize the response
B. To define multiple routes in one function
C. To handle only POST request data
D. To create database models automatically
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 A
Quick Check:
Multiple query parameters = multiple inputs [OK]
Hint: Multiple query parameters let you send many inputs in URL [OK]
Common Mistakes:
Confusing query parameters with request body
Thinking multiple query parameters define routes
Assuming query parameters only work with POST
2. Which of the following is the correct way to declare two query parameters name (string) and age (integer) in a FastAPI path operation function?
easy
A. def read_user(name: str = Query(...), age: int = Query(...)):
Using Query(...) marks parameters as required query parameters with type hints.
Step 2: Check parameter types and usage
Parameters must have correct types and use Query(...) to be recognized as query parameters.
Final Answer:
def read_user(name: str = Query(...), age: int = Query(...)): -> Option A
Quick Check:
Use Query(...) with correct types for query parameters [OK]
Hint: Use Query(...) with type hints for required query parameters [OK]
Common Mistakes:
Swapping types of parameters
Not using Query for required parameters
Omitting type hints
3. Given this FastAPI endpoint code:
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?
medium
A. {"q": ["apple"]}
B. {"q": "apple,banana"}
C. {"q": ["apple", "banana"]}
D. {"q": []}
Solution
Step 1: Understand List query parameters in FastAPI
Using List[str] with Query([]) allows multiple values for the same query key to be collected into a list.
Step 2: Analyze the URL query parameters
The URL has q=apple and q=banana, so FastAPI collects both into a list.
Final Answer:
{"q": ["apple", "banana"]} -> Option C
Quick Check:
Multiple query keys = list of values [OK]
Hint: Multiple same keys in URL become list in FastAPI [OK]
Common Mistakes:
Expecting a single string with commas
Getting only the first value
Getting an empty list
4. What is wrong with this FastAPI endpoint code that tries to accept two query parameters 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}
medium
A. The route path should not end with a slash
B. The function must be async
C. Missing Query() for both parameters
D. The parameter age should use Optional[int] for optional query
Solution
Step 1: Check optional query parameter typing
In FastAPI, optional parameters should use Optional[type] or type | None to mark them optional properly.
Step 2: Analyze age: int = None
Just setting default to None is not enough; the type hint should be Optional[int] or int | None for FastAPI to treat it as optional.
Final Answer:
The parameter age should use Optional[int] for optional query -> Option D
Quick Check:
Optional query params need Optional[type] or type | None [OK]
Hint: Use Optional[int] or int | None for optional query params [OK]
Common Mistakes:
Assuming default None alone makes param optional
Forgetting to import Optional
Thinking async is required for all endpoints
5. You want to create a FastAPI endpoint that accepts multiple optional query parameters: tags (list of strings), limit (integer, default 10), and search (optional string). Which of the following function signatures correctly implements this?
hard
A. def get_items(tags: List[str] = Query([]), limit: int = 10, search: str = None):
B. def get_items(tags: List[str] = Query([]), limit: int = Query(10), search: Optional[str] = Query(None)):
C. def get_items(tags: List[str] = [], limit: int = 10, search: str = ''):
D. def get_items(tags: List[str], limit: int = Query(10), search: Optional[str] = Query(None)):
Solution
Step 1: Use Query() for query parameters with defaults
FastAPI requires using Query() to specify default values and metadata for query parameters.
Step 2: Correctly type optional parameters
Use Optional[str] or str | None with Query(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)): uses Query([]) for list default, Query(10) for limit default, and Optional[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 B
Quick Check:
Use Query() with correct types and defaults for multiple optional queries [OK]
Hint: Use Query() with defaults and Optional for optional query params [OK]
Common Mistakes:
Using mutable default [] without Query()
Not marking optional string with Optional
Omitting Query() for default values
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.