0
0
FastAPIframework~10 mins

Custom middleware creation in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom middleware creation
Request received by FastAPI
Middleware intercepts request
Middleware processes or modifies request
Pass request to next handler (route or next middleware)
Response generated by route
Middleware intercepts response
Middleware processes or modifies response
Response sent back to client
Middleware sits between the client and route handlers, intercepting requests and responses to process or modify them.
Execution Sample
FastAPI
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class CustomMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        print("Before request")
        response = await call_next(request)
        print("After response")
        return response

app.add_middleware(CustomMiddleware)
This code creates a middleware that prints messages before and after processing each request.
Execution Table
StepActionRequest StateResponse StateOutput/Effect
1Request received by FastAPIRequest object createdNo response yetIncoming request starts processing
2Middleware dispatch startsRequest passed to middlewareNo response yetPrints 'Before request'
3Middleware calls next handlerRequest forwarded to route handlerNo response yetRoute processes request
4Route generates responseRequest handledResponse object createdResponse ready to return
5Middleware resumes after call_nextRequest handledResponse receivedPrints 'After response'
6Middleware returns responseRequest handledResponse returnedResponse sent to client
7Request cycle endsNo active requestResponse sentCycle complete
💡 Response sent back to client, middleware cycle complete
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
requestNoneRequest objectRequest objectRequest objectRequest handled
responseNoneNoneNoneResponse objectResponse sent
Key Moments - 3 Insights
Why do we call 'await call_next(request)' inside the middleware?
Because 'call_next' passes the request to the next handler (like the route). Without calling it, the request would stop and no response would be generated. See execution_table step 3.
What happens if we modify the response after 'call_next'?
The middleware can change the response before sending it back to the client. This happens after step 5 in the execution_table, where the middleware can add headers or change content.
Can middleware stop the request from reaching the route?
Yes, if middleware returns a response directly without calling 'call_next', the route is skipped. This is not shown in the example but is important to know.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed first when a request is processed?
A"After response"
B"Response sent"
C"Before request"
D"Request received"
💡 Hint
Check step 2 in the execution_table where middleware starts processing.
At which step does the route handler generate the response?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look for when the response object is created in the execution_table.
If middleware does not call 'call_next', what happens?
AThe middleware returns a response directly, skipping the route
BAn error occurs automatically
CThe request is forwarded to the route
DThe response is delayed but eventually sent
💡 Hint
Refer to key_moments about middleware behavior when skipping call_next.
Concept Snapshot
Custom middleware in FastAPI intercepts requests and responses.
Define a class inheriting BaseHTTPMiddleware.
Override async dispatch(request, call_next).
Call 'await call_next(request)' to continue.
Modify request or response as needed.
Add middleware with app.add_middleware().
Full Transcript
Custom middleware in FastAPI acts like a checkpoint between the client and your route handlers. When a request comes in, the middleware's dispatch method runs first. It can do things before the request reaches your route, like logging or modifying the request. Then it calls 'await call_next(request)' to pass the request to the next handler, usually your route. After the route creates a response, the middleware can again process or change the response before sending it back to the client. This lets you add features like logging, headers, or authentication checks in one place. Remember, if you don't call 'call_next', the request won't reach your route and the middleware must return a response directly. This flow ensures you can control how requests and responses move through your app.