Sometimes, your API needs to send different kinds of answers depending on the situation. Using multiple response types lets your app do that clearly and safely.
Multiple response types in FastAPI
from fastapi import FastAPI, Response from fastapi.responses import JSONResponse, PlainTextResponse app = FastAPI() @app.get("/item/{item_id}", responses={ 200: {"content": {"application/json": {}}}, 404: {"content": {"text/plain": {}}} }) async def read_item(item_id: int): if item_id == 1: return JSONResponse(content={"item_id": item_id, "name": "Item One"}) else: return PlainTextResponse("Item not found", status_code=404)
Use the responses parameter in the route decorator to declare possible response types.
Return the appropriate response class like JSONResponse or PlainTextResponse inside the function.
from fastapi.responses import JSONResponse, PlainTextResponse @app.get("/status") async def get_status(success: bool): if success: return JSONResponse(content={"status": "ok"}) else: return PlainTextResponse("Failed to get status", status_code=400)
@app.get("/data", responses={ 200: {"content": {"application/json": {}}}, 202: {"content": {"text/plain": {}}} }) async def get_data(ready: bool): if ready: return {"data": [1, 2, 3]} else: return PlainTextResponse("Data processing", status_code=202)
This FastAPI app has one endpoint that returns user info as JSON if found, or a plain text error if not.
from fastapi import FastAPI from fastapi.responses import JSONResponse, PlainTextResponse app = FastAPI() @app.get("/user/{user_id}", responses={ 200: {"content": {"application/json": {}}}, 404: {"content": {"text/plain": {}}} }) async def get_user(user_id: int): users = {1: "Alice", 2: "Bob"} if user_id in users: return JSONResponse(content={"user_id": user_id, "name": users[user_id]}) else: return PlainTextResponse("User not found", status_code=404)
Always specify the responses dict to help API docs show all response types.
Use response classes from fastapi.responses to control content type and status code.
Returning plain dicts defaults to JSON response automatically.
Multiple response types let your API send different formats based on conditions.
Use responses in the route decorator to declare them.
Return the right response class inside your function to match the declared types.
Practice
Solution
Step 1: Understand response types in FastAPI
Multiple response types let an API send different formats like JSON or HTML depending on the request or logic.Step 2: Identify the purpose
This flexibility helps clients get the response format they expect or need.Final Answer:
To allow the API to send different response formats based on conditions -> Option BQuick Check:
Multiple response types = different formats [OK]
- Thinking it speeds up response time
- Believing it restricts to one format
- Confusing with database schema generation
Solution
Step 1: Review FastAPI response declaration syntax
FastAPI uses the 'responses' parameter with status codes and content types as keys.Step 2: Identify correct syntax for multiple types
@app.get('/items', responses={200: {'content': {'application/json': {}, 'text/html': {}}}}) correctly shows multiple content types under the 200 status code.Final Answer:
@app.get('/items', responses={200: {'content': {'application/json': {}, 'text/html': {}}}}) -> Option DQuick Check:
responses param with content dict = @app.get('/items', responses={200: {'content': {'application/json': {}, 'text/html': {}}}}) [OK]
- Using non-existent parameters like response_type
- Declaring only one content type when multiple needed
- Incorrect dictionary structure in responses
return HTMLResponse(content='Hello') is used?from fastapi import FastAPI
from fastapi.responses import JSONResponse, HTMLResponse
app = FastAPI()
@app.get('/greet', responses={200: {'content': {'application/json': {}, 'text/html': {}}}})
async def greet(html: bool = False):
if html:
return HTMLResponse(content='Hello')
return JSONResponse(content={'message': 'Hello'})Solution
Step 1: Check the return type when html=True
The function returns HTMLResponse with content 'Hello' when html is True.Step 2: Identify the content type of HTMLResponse
HTMLResponse sets the content type to 'text/html'.Final Answer:
text/html -> Option AQuick Check:
HTMLResponse = text/html [OK]
- Assuming JSONResponse is always returned
- Confusing content type with return value
- Ignoring the condition that triggers HTMLResponse
from fastapi import FastAPI
from fastapi.responses import JSONResponse, PlainTextResponse
app = FastAPI()
@app.get('/data', responses={200: {'content': {'application/json': {}, 'text/plain': {}}}})
async def data(response_type: str):
if response_type == 'json':
return JSONResponse(content={'key': 'value'})
else:
return 'Just plain text'Solution
Step 1: Check return types in the function
When response_type is not 'json', the function returns a plain string instead of a Response object.Step 2: Understand FastAPI response requirements
FastAPI expects a Response object like PlainTextResponse for non-JSON responses to set headers correctly.Final Answer:
Returning a plain string instead of a Response object for plain text -> Option CQuick Check:
Plain string return needs PlainTextResponse [OK]
- Returning raw strings instead of Response objects
- Ignoring response content type headers
- Assuming async is not needed
?format=html is given. Which approach correctly implements this with multiple response types?from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, HTMLResponse
app = FastAPI()
@app.get('/info', responses={200: {'content': {'application/json': {}, 'text/html': {}}}})
async def info(request: Request):
format = request.query_params.get('format')
if format == 'html':
# What to return here?
else:
return JSONResponse(content={'info': 'data'})Solution
Step 1: Check the condition for HTML format
If the query parameter 'format' equals 'html', the route should return an HTML response.Step 2: Use the correct response class for HTML
HTMLResponse sets the content type to 'text/html' and sends HTML content properly.Final Answer:
return HTMLResponse(content='<h1>Info</h1>') -> Option AQuick Check:
HTMLResponse for HTML output = return HTMLResponse(content='<h1>Info</h1>') [OK]
- Returning dict with HTML string instead of HTMLResponse
- Using JSONResponse with HTML content type
- Setting wrong media_type in Response
Ready to prove it?
Pass the test and this pattern moves unknown
