Consider this FastAPI endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_item(q: str):
return {"q": q}What is the response if the client calls /items/ without the q parameter?
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_item(q: str): return {"q": q}
Think about what FastAPI does when a required parameter is not provided.
FastAPI automatically validates required query parameters. If a required parameter like 'q' is missing, it returns a 422 error indicating the request is invalid.
Which of the following FastAPI endpoint definitions correctly makes q a required query parameter?
Required parameters do not have default values.
In FastAPI, a query parameter without a default value is required. Adding a default value makes it optional.
Given this FastAPI endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/search")
async def search(q: str):
return {"query": q.upper()}What is the JSON response when the client calls /search?q=fastapi?
from fastapi import FastAPI app = FastAPI() @app.get("/search") async def search(q: str): return {"query": q.upper()}
Look at how the parameter q is used inside the function.
The function returns the uppercase version of the query parameter q. So the response JSON has the value "FASTAPI".
Examine this code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
async def get_items(q: str = None):
return {"q": q.upper()}When calling /items without query parameters, what error occurs and why?
from fastapi import FastAPI app = FastAPI() @app.get("/items") async def get_items(q: str = None): return {"q": q.upper()}
Consider what happens when q is None and you call upper().
Since q defaults to None, calling q.upper() raises an AttributeError because NoneType has no upper method.
In FastAPI, you want a query parameter q that is required but also has a default value if not provided. Which statement is true?
Think about what 'required' means in FastAPI query parameters.
In FastAPI, if a query parameter has a default value, it is optional. Required means no default value is set.