Custom middleware for FastAPI application

FastAPI is a Python web framework for building APIs. By using a middleware, we are able to process request and response before/after they get handled by the application.

Implement custom middleware

Starlette is a lightweight ASGI framework/toolkit on which FastAPI is based. It provides BaseHTTPMiddleware class for us to implement custom middleware. It’s required to override the async def dispatch(request, call_next) method.

from starlette.middleware.base import BaseHTTPMiddleware

class CustomHeaderMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, header_value='Example'):
        self.header_value = header_value

    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers['Custom'] = self.header_value
        return response

The example middleware above simply adds a Custom header to the response.

FastAPI also supports using decorator to create a middleware :

async def custom_middleware(request: Request, call_next):
	response = await call_next(request)
	return response

It should have the same effect as overriding the dispatch method. I personally prefer the below way to programmatically add the middleware to the FastAPI application.

Add middleware to FastAPI

from fastapi import FastAPI

app = FastAPI()

app.add_middleware(CustomHeaderMiddleware, header_value='Hello')