Bird
Raised Fist0
FastAPIframework~20 mins

Custom response classes in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Custom 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 of this FastAPI endpoint with a custom response class?

Consider this FastAPI endpoint using a custom response class:

from fastapi import FastAPI, Response

app = FastAPI()

class CustomTextResponse(Response):
    media_type = "text/custom"

@app.get("/custom", response_class=CustomTextResponse)
async def custom_response():
    return "Hello Custom!"

What will the client receive as the Content-Type header and body?

FastAPI
from fastapi import FastAPI, Response

app = FastAPI()

class CustomTextResponse(Response):
    media_type = "text/custom"

@app.get("/custom", response_class=CustomTextResponse)
async def custom_response():
    return "Hello Custom!"
AContent-Type: text/custom with body 'Hello Custom!'
BContent-Type: application/json with body '"Hello Custom!"'
CContent-Type: text/plain with body 'Hello Custom!'
DContent-Type: text/custom with empty body
Attempts:
2 left
💡 Hint

Check the media_type attribute in the custom response class.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a custom JSON response class in FastAPI?

You want to create a custom JSON response class that sets media_type to application/vnd.api+json. Which code snippet is correct?

A
class CustomJSONResponse(Response):
    media_type = "application/json"

    def render(self, content: Any) -> str:
        return json.dumps(content)
B
class CustomJSONResponse(JSONResponse):
    media_type = "application/vnd.api+json"
C
class CustomJSONResponse(Response):
    media_type = "application/vnd.api+json"

    def render(self, content: Any) -> bytes:
        import json
        return json.dumps(content).encode("utf-8")
D
class CustomJSONResponse(Response):
    media_type = "application/vnd.api+json"

    def render(self, content: Any) -> str:
        return json.dumps(content)
Attempts:
2 left
💡 Hint

FastAPI's JSONResponse already handles JSON encoding.

🔧 Debug
advanced
2:00remaining
Why does this custom response class cause a runtime error?

Examine this code snippet:

from fastapi import FastAPI, Response

app = FastAPI()

class MyResponse(Response):
    media_type = "text/plain"

    def render(self, content):
        return content

@app.get("/test", response_class=MyResponse)
async def test():
    return "Hello"

What error will occur and why?

FastAPI
from fastapi import FastAPI, Response

app = FastAPI()

class MyResponse(Response):
    media_type = "text/plain"

    def render(self, content):
        return content

@app.get("/test", response_class=MyResponse)
async def test():
    return "Hello"
ANo error, returns plain text 'Hello'
BSyntaxError due to missing colon in render method
CTypeError because render must return bytes, not str
DRuntimeError because media_type is invalid
Attempts:
2 left
💡 Hint

Check the return type expected by render in FastAPI's Response classes.

❓ state_output
advanced
2:00remaining
What is the response body when using this custom XML response class?

Given this FastAPI app:

from fastapi import FastAPI, Response

app = FastAPI()

class XMLResponse(Response):
    media_type = "application/xml"

    def render(self, content: dict) -> bytes:
        xml = ""
        for key, value in content.items():
            xml += f"<{key}>{value}"
        xml += ""
        return xml.encode("utf-8")

@app.get("/xml", response_class=XMLResponse)
async def get_xml():
    return {"name": "Alice", "age": 30}

What will the client receive as the response body?

FastAPI
from fastapi import FastAPI, Response

app = FastAPI()

class XMLResponse(Response):
    media_type = "application/xml"

    def render(self, content: dict) -> bytes:
        xml = "<root>"
        for key, value in content.items():
            xml += f"<{key}>{value}</{key}>"
        xml += "</root>"
        return xml.encode("utf-8")

@app.get("/xml", response_class=XMLResponse)
async def get_xml():
    return {"name": "Alice", "age": 30}
A<root><name>Alice</name><age>30</age></root>
B<root>{"name": "Alice", "age": 30}</root>
C{"name": "Alice", "age": 30}
D<root><name>Alice</name><age>"30"</age></root>
Attempts:
2 left
💡 Hint

Look at how the render method builds the XML string.

🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI custom response classes is TRUE?

Choose the correct statement about creating and using custom response classes in FastAPI.

AFastAPI automatically converts any return value to bytes, so <code>render</code> is optional.
BYou can use any Python class as a response_class if it has a <code>media_type</code> attribute.
CCustom response classes can override <code>media_type</code> but cannot change the response body format.
DCustom response classes must always subclass <code>Response</code> and implement <code>render</code> returning bytes.
Attempts:
2 left
💡 Hint

Think about what FastAPI expects from response classes regarding data encoding.

Practice

(1/5)
1. What is the main purpose of using Custom response classes in FastAPI?
easy
A. To handle user authentication
B. To create database models automatically
C. To control how FastAPI sends data back to the client
D. To manage background tasks

Solution

  1. Step 1: Understand the role of response classes

    Response classes in FastAPI define how data is formatted and sent back to the client, such as JSON, HTML, or plain text.
  2. Step 2: Identify the correct purpose

    Custom response classes let you control the exact format and headers of the response, improving clarity and compatibility.
  3. Final Answer:

    To control how FastAPI sends data back to the client -> Option C
  4. Quick Check:

    Custom response classes = control response format [OK]
Hint: Response classes define output format in FastAPI [OK]
Common Mistakes:
  • Confusing response classes with database models
  • Thinking they handle authentication
  • Assuming they manage background tasks
2. Which of the following is the correct way to use a custom response class to return plain text in FastAPI?
easy
A. return PlainTextResponse(content="Hello World")
B. return JSONResponse(content="Hello World")
C. return HTMLResponse(content=123)
D. return FileResponse(path="hello.txt")

Solution

  1. Step 1: Identify the correct response class for plain text

    FastAPI provides PlainTextResponse to send plain text content.
  2. Step 2: Check the usage syntax

    The correct syntax is to pass the text string as the content argument.
  3. Final Answer:

    return PlainTextResponse(content="Hello World") -> Option A
  4. Quick Check:

    PlainTextResponse with content string = return PlainTextResponse(content="Hello World") [OK]
Hint: Use PlainTextResponse for text content [OK]
Common Mistakes:
  • Using JSONResponse for plain text
  • Passing non-string content to HTMLResponse
  • Using FileResponse for text content
3. Given the code below, what will be the response content type sent to the client?
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def read_root():
    return "

Welcome

"
medium
A. text/html
B. application/json
C. text/plain
D. application/octet-stream

Solution

  1. Step 1: Identify the response class used

    The route uses response_class=HTMLResponse, which sets the content type to HTML.
  2. Step 2: Understand the content type sent

    HTMLResponse sends content with the header Content-Type: text/html.
  3. Final Answer:

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

    HTMLResponse = text/html content type [OK]
Hint: HTMLResponse sets content type to text/html [OK]
Common Mistakes:
  • Assuming JSON is default content type
  • Confusing plain text with HTML content type
  • Ignoring the response_class parameter
4. What is wrong with this FastAPI endpoint using a custom response class?
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/data")
async def get_data():
    return JSONResponse(content=[1, 2, 3], status_code="200")
medium
A. Missing return type annotation
B. content must be a dictionary, not a list
C. JSONResponse cannot be used in async functions
D. status_code should be an integer, not a string

Solution

  1. Step 1: Check the status_code argument type

    Status codes must be integers, but here it is passed as a string "200".
  2. Step 2: Understand the impact of wrong type

    Passing a string causes a runtime error or unexpected behavior in FastAPI.
  3. Final Answer:

    status_code should be an integer, not a string -> Option D
  4. Quick Check:

    Status code must be int, not str [OK]
Hint: Use integer for status_code, not string [OK]
Common Mistakes:
  • Passing status_code as string
  • Thinking content must be dict only
  • Believing JSONResponse can't be async
5. You want to create a FastAPI endpoint that returns a CSV file for download using a custom response class. Which approach correctly sets the response to send a CSV file named "report.csv" with content "name,age\nAlice,30"?
hard
A. Use JSONResponse with content as CSV string and set media_type to 'text/csv'
B. Use StreamingResponse with content as bytes and set headers for CSV download
C. Use PlainTextResponse with content as CSV string and no headers
D. Use HTMLResponse with CSV content inside <pre> tags

Solution

  1. Step 1: Choose the correct response class for file download

    StreamingResponse is suitable for sending files or streams with custom headers.
  2. Step 2: Set content and headers properly

    Content should be bytes, and headers must include Content-Disposition to prompt file download with the filename.
  3. Final Answer:

    Use StreamingResponse with content as bytes and set headers for CSV download -> Option B
  4. Quick Check:

    StreamingResponse + headers = file download [OK]
Hint: Use StreamingResponse with headers for file downloads [OK]
Common Mistakes:
  • Using JSONResponse for CSV files
  • Not setting Content-Disposition header
  • Using HTMLResponse for file content
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