Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a query parameter in FastAPI.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: [1] = None): return {"query": q}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using an integer type for a text query parameter.
✗ Incorrect
The query parameter q is defined as a string type to accept text filters.
2fill in blank
mediumComplete the code to filter items by a query parameter.
FastAPI
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
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the list name instead of the query parameter for filtering.
✗ Incorrect
The code checks if the query string q is part of each item to filter the list.
3fill in blank
hardFix the error in the query parameter default value to make it optional.
FastAPI
@app.get("/users/") async def read_users(name: [1]): return {"name": name}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using empty string as default makes parameter required with empty value.
✗ Incorrect
Setting the default to None makes the query parameter optional.
4fill in blank
hardFill both blanks to filter items by minimum and maximum price query parameters.
FastAPI
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 filtered Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys like "name" or "cost" which do not exist.
✗ Incorrect
Both blanks should access the "price" key to filter by price range.
5fill in blank
hardFill all three blanks to create a filtered dictionary of items with names and prices above a threshold.
FastAPI
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 result Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys like "cost" or mixing keys incorrectly.
✗ Incorrect
The dictionary keys are item names and values are prices filtered by price greater than min_price.