Bird
Raised Fist0
FastAPIframework~20 mins

Multiple response types in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Multiple Response Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when requesting JSON from this FastAPI endpoint?

Consider this FastAPI endpoint that returns different response types based on the accept header.

from fastapi import FastAPI, Response
app = FastAPI()

@app.get("/data")
async def get_data(response: Response, accept: str = "application/json"):
    if accept == "application/xml":
        response.media_type = "application/xml"
        return "<data>Hello</data>"
    return {"message": "Hello"}

What will the client receive if it sends a request with accept header set to application/json?

FastAPI
from fastapi import FastAPI, Response
app = FastAPI()

@app.get("/data")
async def get_data(response: Response, accept: str = "application/json"):
    if accept == "application/xml":
        response.media_type = "application/xml"
        return "<data>Hello</data>"
    return {"message": "Hello"}
AA plain text response with body {"message": "Hello"} and content-type text/plain
BAn XML response with body <data>Hello</data> and content-type application/xml
CA 404 Not Found error because the accept header is not handled
DA JSON response with body {"message": "Hello"} and content-type application/json
Attempts:
2 left
💡 Hint

Check the default value of the accept parameter and what the function returns in that case.

📝 Syntax
intermediate
2:00remaining
Which option correctly sets multiple response types in FastAPI?

You want to create a FastAPI endpoint that can return either JSON or plain text based on a query parameter. Which code snippet correctly implements this?

A
from fastapi import FastAPI, Response
app = FastAPI()

@app.get("/item")
async def item(text: bool = False):
    if text:
        return Response(content="Hello", media_type="text/plain")
    return {"message": "Hello"}
B
from fastapi import FastAPI
app = FastAPI()

@app.get("/item")
async def item(text: bool = False):
    if text:
        return {"message": "Hello"}
    return Response(content="Hello", media_type="text/plain")
C
from fastapi import FastAPI, Response
app = FastAPI()

@app.get("/item")
async def item(text: bool = False):
    if text:
        return Response(content="Hello")
    return {"message": "Hello"}
D
from fastapi import FastAPI
app = FastAPI()

@app.get("/item")
async def item(text: bool = False):
    return Response(content="Hello", media_type="text/plain")
Attempts:
2 left
💡 Hint

Remember that to return plain text, you must specify the media_type in Response.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI endpoint always return JSON even when requesting XML?

Look at this FastAPI endpoint:

from fastapi import FastAPI
app = FastAPI()

@app.get("/info")
async def info(accept: str):
    if accept == "application/xml":
        return "<info>Data</info>"
    return {"info": "Data"}

When a client sends the header accept: application/xml, the response is still JSON. Why?

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/info")
async def info(accept: str):
    if accept == "application/xml":
        return "<info>Data</info>"
    return {"info": "Data"}
ABecause the accept parameter is not read from headers but from query parameters
BBecause FastAPI does not support XML responses
CBecause returning a string always produces JSON in FastAPI
DBecause the response media type is not set to application/xml, FastAPI defaults to JSON
Attempts:
2 left
💡 Hint

Check how the accept parameter is passed and used.

❓ state_output
advanced
2:00remaining
What is the content-type of the response for this FastAPI endpoint?

Given this FastAPI endpoint:

from fastapi import FastAPI, Response
app = FastAPI()

@app.get("/custom")
async def custom(response: Response):
    response.headers["Content-Type"] = "application/custom"
    return {"data": "value"}

What will be the content-type header in the HTTP response?

FastAPI
from fastapi import FastAPI, Response
app = FastAPI()

@app.get("/custom")
async def custom(response: Response):
    response.headers["Content-Type"] = "application/custom"
    return {"data": "value"}
Atext/plain
Bapplication/custom
Capplication/json
DNo Content-Type header
Attempts:
2 left
💡 Hint

Think about how FastAPI sets content-type when returning a dict.

🧠 Conceptual
expert
3:00remaining
How to correctly handle multiple response types with FastAPI's Response class?

You want to create a FastAPI endpoint that returns JSON by default but can return XML when requested. Which approach correctly handles setting the response content and media type?

AReturn JSON always and set response.headers['Content-Type'] to 'application/xml' when XML is requested.
BReturn a Response object with content as XML string and media_type='application/xml' when XML is requested; otherwise return a dict for JSON.
CReturn a string with XML content and rely on FastAPI to detect media type automatically.
DReturn a dict with XML string inside when XML is requested and set response.media_type to 'application/xml'.
Attempts:
2 left
💡 Hint

Consider how FastAPI determines response content type and how to override it properly.

Practice

(1/5)
1. What is the main purpose of using multiple response types in a FastAPI route?
easy
A. To speed up the API response time by caching
B. To allow the API to send different response formats based on conditions
C. To restrict the API to only one response format
D. To automatically generate database schemas

Solution

  1. 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.
  2. Step 2: Identify the purpose

    This flexibility helps clients get the response format they expect or need.
  3. Final Answer:

    To allow the API to send different response formats based on conditions -> Option B
  4. Quick Check:

    Multiple response types = different formats [OK]
Hint: Multiple response types mean flexible output formats [OK]
Common Mistakes:
  • Thinking it speeds up response time
  • Believing it restricts to one format
  • Confusing with database schema generation
2. Which of the following is the correct way to declare multiple response types in a FastAPI route decorator?
easy
A. @app.get('/items', responses={200: {'content': {'application/json': {}}}})
B. @app.get('/items', response_formats=['json', 'html'])
C. @app.get('/items', response_type=['json', 'html'])
D. @app.get('/items', responses={200: {'content': {'application/json': {}, 'text/html': {}}}})

Solution

  1. Step 1: Review FastAPI response declaration syntax

    FastAPI uses the 'responses' parameter with status codes and content types as keys.
  2. 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.
  3. Final Answer:

    @app.get('/items', responses={200: {'content': {'application/json': {}, 'text/html': {}}}}) -> Option D
  4. Quick Check:

    responses param with content dict = @app.get('/items', responses={200: {'content': {'application/json': {}, 'text/html': {}}}}) [OK]
Hint: Use 'responses' with content dict for multiple types [OK]
Common Mistakes:
  • Using non-existent parameters like response_type
  • Declaring only one content type when multiple needed
  • Incorrect dictionary structure in responses
3. Given this FastAPI route, what will be the response content type if 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'})
medium
A. text/html
B. application/json
C. application/xml
D. text/plain

Solution

  1. Step 1: Check the return type when html=True

    The function returns HTMLResponse with content 'Hello' when html is True.
  2. Step 2: Identify the content type of HTMLResponse

    HTMLResponse sets the content type to 'text/html'.
  3. Final Answer:

    text/html -> Option A
  4. Quick Check:

    HTMLResponse = text/html [OK]
Hint: HTMLResponse means content type text/html [OK]
Common Mistakes:
  • Assuming JSONResponse is always returned
  • Confusing content type with return value
  • Ignoring the condition that triggers HTMLResponse
4. Identify the error in this FastAPI route that tries to return multiple response types:
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'
medium
A. responses dictionary is incorrectly formatted
B. Missing import for PlainTextResponse
C. Returning a plain string instead of a Response object for plain text
D. Function should not be async

Solution

  1. 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.
  2. Step 2: Understand FastAPI response requirements

    FastAPI expects a Response object like PlainTextResponse for non-JSON responses to set headers correctly.
  3. Final Answer:

    Returning a plain string instead of a Response object for plain text -> Option C
  4. Quick Check:

    Plain string return needs PlainTextResponse [OK]
Hint: Return Response objects, not raw strings for non-JSON [OK]
Common Mistakes:
  • Returning raw strings instead of Response objects
  • Ignoring response content type headers
  • Assuming async is not needed
5. You want a FastAPI route to return JSON by default but HTML if a query parameter ?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'})
hard
A. return HTMLResponse(content='

Info

')
B. return {'info': '

Info

'}
C. return JSONResponse(content={'info': '

Info

'})
D. return Response(content='

Info

', media_type='application/json')

Solution

  1. Step 1: Check the condition for HTML format

    If the query parameter 'format' equals 'html', the route should return an HTML response.
  2. Step 2: Use the correct response class for HTML

    HTMLResponse sets the content type to 'text/html' and sends HTML content properly.
  3. Final Answer:

    return HTMLResponse(content='<h1>Info</h1>') -> Option A
  4. Quick Check:

    HTMLResponse for HTML output = return HTMLResponse(content='<h1>Info</h1>') [OK]
Hint: Use HTMLResponse to send HTML content explicitly [OK]
Common Mistakes:
  • Returning dict with HTML string instead of HTMLResponse
  • Using JSONResponse with HTML content type
  • Setting wrong media_type in Response
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard