In FastAPI, query parameters are often used to filter data. Why is this approach useful?
Think about how filtering helps reduce the amount of data sent over the network.
Query parameters let clients ask for only the data they need. This saves bandwidth and speeds up responses by not sending extra data.
Given this FastAPI endpoint, what is the output when called with ?category=books?
from fastapi import FastAPI, Query app = FastAPI() items = [ {"id": 1, "category": "books"}, {"id": 2, "category": "electronics"}, {"id": 3, "category": "books"} ] @app.get("/items") def read_items(category: str | None = Query(None)): if category: return [item for item in items if item["category"] == category] return items
Look at how the list comprehension filters items by category.
The endpoint returns only items where the category matches the query parameter. Here, it returns items with category 'books'.
Which code snippet correctly defines an optional query parameter named status with a default value of None?
Consider modern Python typing and FastAPI's Query usage.
Option B uses Python 3.10+ union type and FastAPI's Query to set an optional query parameter with default None.
Consider this code snippet. Why does filtering by color not work?
from fastapi import FastAPI
app = FastAPI()
items = [{"id": 1, "color": "red"}, {"id": 2, "color": "blue"}]
@app.get("/items")
def read_items(color: str):
return [item for item in items if item["color"] == color]Think about what happens if the client does not provide the 'color' query parameter.
The 'color' parameter is required without a default, so if the client omits it, FastAPI returns a validation error.
Analyze the code and determine the value of the variable filtered after calling the endpoint with query parameter min_price=50.
from fastapi import FastAPI, Query app = FastAPI() products = [ {"id": 1, "price": 30}, {"id": 2, "price": 50}, {"id": 3, "price": 70} ] @app.get("/products") def get_products(min_price: int = Query(0)): filtered = [p for p in products if p["price"] >= min_price] return filtered
Check which products have price greater than or equal to 50.
The list comprehension filters products with price >= 50, so products with id 2 and 3 are included.