0
0
FastAPIframework~20 mins

Custom response classes in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 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.