Complete the code to define a query parameter in FastAPI.
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: [1] = None): return {"query": q}
The query parameter q is defined as a string type to accept text filters.
Complete the code to filter items by a query parameter.
items = ["apple", "banana", "cherry"] @app.get("/items/") async def read_items(q: str = None): if q: return [item for item in items if [1] in item] return items
The code checks if the query string q is part of each item to filter the list.
Fix the error in the query parameter default value to make it optional.
@app.get("/users/") async def read_users(name: [1]): return {"name": name}
Setting the default to None makes the query parameter optional.
Fill both blanks to filter items by minimum and maximum price query parameters.
items = [{"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "cherry", "price": 7}]
@app.get("/items/")
async def read_items(min_price: int = None, max_price: int = None):
filtered = [item for item in items if (min_price is None or item[[1]] >= min_price) and (max_price is None or item[[2]] <= max_price)]
return filteredBoth blanks should access the "price" key to filter by price range.
Fill all three blanks to create a filtered dictionary of items with names and prices above a threshold.
items = [{"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "cherry", "price": 7}]
@app.get("/items/")
async def read_items(min_price: int = 4):
result = {item[[1]]: item[[2]] for item in items if item[[3]] > min_price}
return resultThe dictionary keys are item names and values are prices filtered by price greater than min_price.
