Consider this FastAPI endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: str):
return {"query": q}What will the response be when you visit /items/?q=hello?
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str): return {"query": q}
Query parameters are passed after the ? in the URL and matched by name.
The parameter q is declared as a string query parameter. When you visit /items/?q=hello, FastAPI assigns q the value "hello". The function returns a dictionary with key query and value hello.
In FastAPI, how do you declare a query parameter q that is optional and defaults to None?
Optional parameters need a default value in Python function definitions.
In FastAPI, to make a query parameter optional, you assign it a default value like None. Option C does this correctly. Option C is missing the default value and will cause an error unless Optional is imported and default is set. Option C is required. Option C defaults to empty string, which is not None.
Given this FastAPI endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/search/")
async def search_items(q: str = "default"):
return {"query": q}What will be the response when you visit /search/ without any query parameters?
from fastapi import FastAPI app = FastAPI() @app.get("/search/") async def search_items(q: str = "default"): return {"query": q}
Default values are used when no value is provided.
The parameter q has a default value of "default". When no query parameter is given, FastAPI uses this default. So the response contains {"query": "default"}.
Consider these FastAPI endpoint definitions. Which one will cause a runtime error when accessed without query parameters?
Check if the parameter has a default value or is optional.
Option A uses Optional[str] but does not provide a default value, so FastAPI treats q as required. Calling without query parameter causes a 422 error. Option A is required but will cause a validation error, not runtime error. Option A and C have defaults and work fine.
Given this endpoint:
from fastapi import FastAPI
from typing import List
app = FastAPI()
@app.get("/items/")
async def read_items(q: List[str] = []):
return {"queries": q}What will be the output when the URL is /items/?q=foo&q=bar&q=baz?
from fastapi import FastAPI from typing import List app = FastAPI() @app.get("/items/") async def read_items(q: List[str] = []): return {"queries": q}
FastAPI can collect multiple query parameters with the same name into a list.
When a query parameter is declared as a list, FastAPI collects all values with that name into the list. So q=foo&q=bar&q=baz becomes ["foo", "bar", "baz"].