0
0
FastAPIframework~10 mins

Custom middleware creation 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 middleware in FastAPI.

FastAPI
from starlette.middleware.base import [1]
Drag options to blanks, or click blank then click option'
ABaseHTTPMiddleware
BMiddleware
CRequestMiddleware
DCustomMiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Middleware' which is a different concept.
Trying to import a non-existent 'RequestMiddleware'.
2fill in blank
medium

Complete the code to define the async method that processes each request in custom middleware.

FastAPI
class CustomMiddleware(BaseHTTPMiddleware):
    async def [1](self, request, call_next):
        response = await call_next(request)
        return response
Drag options to blanks, or click blank then click option'
Aprocess_request
Bmiddleware_call
Chandle
Ddispatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'process_request' which is not recognized by FastAPI middleware.
Naming the method 'handle' or 'middleware_call' which are incorrect.
3fill in blank
hard

Fix the error in the middleware code by completing the missing import for the Request class.

FastAPI
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import [1]

app = FastAPI()
Drag options to blanks, or click blank then click option'
AMiddleware
BResponse
CRequest
DHTTPMiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Importing 'Response' instead of 'Request'.
Trying to import 'Middleware' which is not a class here.
4fill in blank
hard

Fill both blanks to add the custom middleware to the FastAPI app.

FastAPI
app = FastAPI()
app.add_middleware([1], app=[2])
Drag options to blanks, or click blank then click option'
ACustomMiddleware
BBaseHTTPMiddleware
Cmiddleware_class
Dapp
Attempts:
3 left
💡 Hint
Common Mistakes
Passing BaseHTTPMiddleware directly instead of the custom class.
Passing a wrong keyword argument name or value.
5fill in blank
hard

Fill all three blanks to modify the response headers inside the custom middleware.

FastAPI
class CustomMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers[[1]] = [2]
        response.headers[[3]] = "CustomValue"
        return response
Drag options to blanks, or click blank then click option'
A"X-Custom-Header"
B"Processed"
C"X-Another-Header"
D"Ignored"
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-string keys or values for headers.
Mixing header names and values in the wrong blanks.