Skip to main content

Understanding Middleware

Middleware in FastAPI is a crucial piece of the puzzle when it comes to building web applications. In simple terms, middleware is a piece of software that sits between the server and the application. It can process requests before they reach your application, or responses before they return to the client.

What is Middleware?

Middleware is used to perform functions such as:

  • Logging
  • Authentication
  • Session management
  • Cross-Origin Resource Sharing (CORS)

Middleware is executed in the order it is added. The first middleware added is the first to process the request and the last to process the response.

How to Use Middleware in FastAPI

To use middleware in FastAPI, we use the add_middleware function. Here's a simple example:

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

In the above example, we're adding the CORSMiddleware which is used to handle the cross-origin resource sharing (CORS) mechanism.

Creating Custom Middleware

You can create custom middleware according to your requirements. Here's an example of a custom middleware that logs the time taken to process the requests:

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
import time

class TimingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.time()
response = await call_next(request)
end_time = time.time()
process_time = end_time - start_time
response.headers['X-Process-Time'] = str(process_time)
return response

app.add_middleware(TimingMiddleware)

In the above code, we extend the BaseHTTPMiddleware class and override its dispatch method. This method is invoked for every request. We measure the time before and after the call_next method, which calls the next middleware or the actual route function. We then add the processing time to the response headers.

Middleware and Exception Handling

Middleware can also be used to handle exceptions. Here's an example:

from starlette.middleware.errors import ServerErrorMiddleware

app.add_middleware(ServerErrorMiddleware, handler=custom_exception_handler)

In the above example, we add the ServerErrorMiddleware, which catches exceptions and passes them to the custom_exception_handler function. This function should take a request and an exception as arguments, and return a Response.

Conclusion

Middleware is a powerful tool in FastAPI, allowing you to process requests and responses, handle exceptions, manage sessions, and more. With the ability to use built-in middleware or create your own, you can customize your application to suit your needs.