Consider this FastAPI endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: str, limit: int = 10):
return {"q": q, "limit": limit}What will be the JSON response if the URL is /items/?q=book&limit=5?
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str, limit: int = 10): return {"q": q, "limit": limit}
Query parameters in FastAPI are matched by name and type. Default values are used only if the parameter is missing.
The endpoint expects a required string q and an optional integer limit with default 10. Passing q=book and limit=5 sets both accordingly.
Which FastAPI function signature correctly defines two optional query parameters category (string) and page (integer) with default values?
Optional query parameters must have default values. Non-optional parameters without defaults are required.
Option A correctly sets category as optional with default None and page as optional with default 1. Option A misses default for page. Option A makes category required. Option A sets page default to None but type is int, which causes validation error.
Given this endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/search")
async def search_items(q: str, limit: int = "10"):
return {"q": q, "limit": limit}Why does calling /search?q=phone cause a validation error?
from fastapi import FastAPI app = FastAPI() @app.get("/search") async def search_items(q: str, limit: int = "10"): return {"q": q, "limit": limit}
Check the type of default values compared to the declared parameter type.
The parameter limit is declared as int but its default value is a string "10". FastAPI tries to convert the default but fails validation, causing an error.
Consider this FastAPI endpoint:
from fastapi import FastAPI
from typing import List
app = FastAPI()
@app.get("/filter")
async def filter_items(tags: List[str] = []):
return {"tags": tags}What will be the output if the URL is /filter?tags=red&tags=blue?
from fastapi import FastAPI from typing import List app = FastAPI() @app.get("/filter") async def filter_items(tags: List[str] = []): return {"tags": tags}
Multiple query parameters with the same name are parsed as a list.
FastAPI parses repeated query parameters with the same name into a list. So tags=red&tags=blue becomes ["red", "blue"].
When a FastAPI endpoint declares a parameter as tags: List[str], and the request URL contains multiple tags query parameters, how does FastAPI process them?
Think about how lists in function parameters relate to repeated query parameters.
FastAPI automatically collects repeated query parameters with the same name into a list when the parameter type is a list. This allows easy handling of multiple values.