0
0
FastAPIframework~10 mins

Custom response classes in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the base class for custom responses in FastAPI.

FastAPI
from fastapi.responses import [1]
Drag options to blanks, or click blank then click option'
AJSONResponse
BHTMLResponse
CResponse
DRedirectResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing a specific response class like JSONResponse instead of the base Response class.
2fill in blank
medium

Complete the code to create a custom response class named MyResponse inheriting from the base response class.

FastAPI
class MyResponse([1]):
    def __init__(self, content: str):
        super().__init__(content=content, media_type="text/custom")
Drag options to blanks, or click blank then click option'
AResponse
BJSONResponse
CHTMLResponse
DPlainTextResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Inheriting from a specific response class instead of the base Response class.
3fill in blank
hard

Fix the error in the custom response class by completing the method that returns the response body as bytes.

FastAPI
class MyResponse(Response):
    def __init__(self, content: str):
        super().__init__(content=content, media_type="text/custom")

    def [1](self) -> bytes:
        return self.content.encode("utf-8")
Drag options to blanks, or click blank then click option'
Arender
Bget_body
Cto_bytes
Dcontent_bytes
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that FastAPI does not recognize for rendering response content.
4fill in blank
hard

Fill both blanks to create a FastAPI route that returns the custom response with content 'Hello'.

FastAPI
from fastapi import FastAPI

app = [2]()

@app.get("/custom")
async def custom_route():
    return [1]("Hello")  # Use custom response class
Drag options to blanks, or click blank then click option'
AMyResponse
BFastAPI
CResponse
DJSONResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the base Response class instead of the custom one.
Reassigning app incorrectly.
5fill in blank
hard

Fill all three blanks to define a custom response class that sets a custom header and returns content as bytes.

FastAPI
from fastapi.responses import Response

class CustomHeaderResponse([1]):
    def __init__(self, content: str):
        headers = {"X-Custom-Header": [2]
        super().__init__(content=content, media_type="text/custom", headers=headers)

    def [3](self) -> bytes:
        return self.content.encode("utf-8")
Drag options to blanks, or click blank then click option'
AResponse
B"MyValue"
Crender
DJSONResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Not quoting the header value string.
Using the wrong method name instead of render.