Complete the code to define a FastAPI GET endpoint that accepts two query parameters: 'name' and 'age'.
from fastapi import FastAPI app = FastAPI() @app.get("/user") async def get_user(name: str, age: [1]): return {"name": name, "age": age}
The 'age' parameter should be an integer, so we use int as its type.
Complete the code to make the 'age' query parameter optional with a default value of 18.
from fastapi import FastAPI app = FastAPI() @app.get("/user") async def get_user(name: str, age: [1] = 18): return {"name": name, "age": age}
To make 'age' optional with a default, just assign a default value to the type int. Using Optional[int] requires importing Optional and is not necessary here.
Fix the error in the code to correctly accept multiple query parameters 'q' and 'limit'.
from fastapi import FastAPI app = FastAPI() @app.get("/search") async def search(q: str, limit: [1] = 10): return {"query": q, "limit": limit}
The 'limit' parameter should be an integer to specify how many results to return.
Fill both blanks to create a FastAPI endpoint that accepts a list of tags as query parameters.
from fastapi import FastAPI from typing import [1] app = FastAPI() @app.get("/items") async def get_items(tags: [2][str] = []): return {"tags": tags}
To accept multiple query parameters as a list, import and use List from typing.
Fill all three blanks to create a FastAPI endpoint that accepts multiple optional query parameters with default values.
from fastapi import FastAPI from typing import [1], [2] app = FastAPI() @app.get("/filter") async def filter_items(categories: [1][[2][str]] = None, limit: [3] = 5): return {"categories": categories, "limit": limit}
Use Optional to allow categories to be None or a list of strings. The limit parameter is an integer with a default value.