0
0
FastAPIframework~20 mins

Custom middleware creation in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this FastAPI middleware log?

Consider this FastAPI middleware that logs request method and path. What will it print when a GET request is made to /items/5?

FastAPI
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class LogMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        print(f"Request: {request.method} {request.url.path}")
        response = await call_next(request)
        return response

app.add_middleware(LogMiddleware)

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    return {"item_id": item_id}
ARequest: GET /items/{item_id}
BRequest: POST /items/5
CRequest: GET /items/5
DNo output printed
Attempts:
2 left
💡 Hint

Look at the request.method and request.url.path values used in the print statement.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this FastAPI middleware

Which option correctly identifies the syntax error in this middleware code?

FastAPI
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class ErrorMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        return response

app.add_middleware(ErrorMiddleware)

@app.get('/')
async def root():
    return {"message": "Hello"}
Adispatch method missing async keyword
BMissing closing parenthesis in app.add_middleware(ErrorMiddleware
CBaseHTTPMiddleware cannot be subclassed
DRequest parameter missing type annotation
Attempts:
2 left
💡 Hint

Check the parentheses in the app.add_middleware line.

state_output
advanced
2:00remaining
What is the response header after this middleware runs?

This middleware adds a custom header X-Custom with value 42. What will the response headers contain after a request?

FastAPI
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class HeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        response.headers["X-Custom"] = "42"
        return response

app.add_middleware(HeaderMiddleware)

@app.get('/')
async def root():
    return {"hello": "world"}
AResponse headers include 'X-Custom': '24'
BResponse headers include 'x-custom': '42' (lowercase key)
CResponse headers do not include 'X-Custom'
DResponse headers include 'X-Custom': '42'
Attempts:
2 left
💡 Hint

Look at how the header is added to the response object.

🔧 Debug
advanced
2:00remaining
Why does this middleware cause a runtime error?

Examine this middleware code. Why does it cause a runtime error when a request is made?

FastAPI
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class FaultyMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        response = call_next(request)  # Missing await
        return response

app.add_middleware(FaultyMiddleware)

@app.get('/')
async def root():
    return {"msg": "ok"}
Acall_next is a coroutine and must be awaited, missing await causes runtime error
Bdispatch method must not be async
CBaseHTTPMiddleware requires a sync dispatch method
DRequest parameter type is incorrect
Attempts:
2 left
💡 Hint

Check how call_next is called inside dispatch.

🧠 Conceptual
expert
3:00remaining
How does FastAPI middleware affect request processing order?

Given multiple middlewares added in this order: MiddlewareA, then MiddlewareB, which statement best describes the order of dispatch calls and response returns?

A<code>MiddlewareA.dispatch</code> runs first on request, then <code>MiddlewareB.dispatch</code>, response returns back through <code>MiddlewareB</code> then <code>MiddlewareA</code>
B<code>MiddlewareB.dispatch</code> runs first on request, then <code>MiddlewareA.dispatch</code>, response returns back through <code>MiddlewareA</code> then <code>MiddlewareB</code>
CBoth middlewares run their dispatch methods simultaneously
DMiddleware order does not affect dispatch call order
Attempts:
2 left
💡 Hint

Think of middleware as layers wrapping the app, like nested boxes.