How to create and use middleware with FastAPI

overview

FastAPI is a framework with the ability to perform processing between requests and responses using middleware. Middleware provides access to request objects, response objects, and the following middleware functions: Middleware is used within FastAPI route handlers.

Here I will show you how to create middleware with FastAPI using the following versions:

FastAPI v0.100.0
Python v3.11.4
uvicorn v0.22.0

In addition, all the code created this time is posted on GitHub.

How to use middleware

FastAPI uses the app.middleware decorator to use middleware.

from fastapi import FastAPI

app = FastAPI()

@app.middleware("http")
async def my_middleware(request, call_next):
    print('This is an application-level middleware')
    response = await call_next(request)
    return response

The code above creates an application-level middleware named my_middleware. This middleware runs for every request. Using the call_next function will pass the request to the next middleware or route handler.

How to create middleware

The example below creates a middleware named my_middleware.

main.py

from fastapi import FastAPI

app = FastAPI()

@app.middleware("http")
async def my_middleware(request, call_next):
    print('run middleware')
    response = await call_next(request)
    return response

@app.get('/')
async def root():
    return {"message": "Hello, World!"}

Commentary

  • Create FastAPI instance
from fastapi import FastAPI
app = FastAPI()

Import the FastAPI module and create an instance of it.

  • Define middleware functions
@app.middleware("http")
async def my_middleware(request, call_next):
    print('run middleware')
    response = await call_next(request)
    return response

Define a middleware function named my_middleware. This function takes a request object and calls the call_next function to pass processing to the next middleware or route handler.

  • Defining route handlers
@app.get('/')
async def root():
    return {"message": "Hello, World!"}

Define a route handler to handle GET requests to the path /. When a request comes in, it returns an object { message: 'Hello, World!' } as a response.

test

Execute the following command from the terminal.

uvicorn main:app --reload

Then test with the command below.

curl -X GET http://localhost:8000

summary

This article describes how to create middleware using the FastAPI framework. FastAPI is a framework that has the ability to do processing between requests and responses, and middleware plays a central role in this processing. FastAPI uses the app.middleware decorator to define middleware.

The article provides an example of creating an application-level middleware my_middleware. This middleware runs for every request and passes the request to the next middleware or route handler. In order to test the created middleware, we also introduce how to start the uvicorn server and send a request with the curl command.

Combined with FastAPI’s flexible routing capabilities, middleware becomes an important tool in developing web applications.