Middleware for FastAPI

Middleware in FastAPI refers to a way to process requests before they reach your endpoints and responses before they are sent back to the client. Middleware can be used for various purposes, such as logging, authentication, and modifying requests or responses.

Here's a simple example to illustrate the concept of middleware in FastAPI:

Explanation

Middleware in FastAPI is a function that takes three parameters: request, call_next, and response. The request parameter is the incoming request object, call_next is a function that you call to get the response, and response is the outgoing response object.

Example Code

Let's create a simple FastAPI application with a middleware that logs the incoming request and outgoing response.

  1. Install FastAPI and Uvicorn:

    pip install fastapi uvicorn
  2. Create a FastAPI application with middleware:

from fastapi import FastAPI, Request
import time
import uvicorn

app = FastAPI()

# Middleware function
@app.middleware("http")
async def log_requests(request: Request, call_next):
    # Log the request details
    print(f"Incoming request: {request.method} {request.url}")

    # Process the request and get the response
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time

    # Log the response details
    print(f"Outgoing response: {response.status_code} (Processed in {process_time:.2f} seconds)")

    return response

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

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

How it works

  1. Define Middleware: The middleware function log_requests is defined using the @app.middleware("http") decorator. This function will be executed for every incoming HTTP request.

  2. Log Request Details: Before processing the request, the middleware logs the HTTP method and URL of the incoming request.

  3. Call Next: The call_next function is called with the request to continue processing and to get the response.

  4. Log Response Details: After getting the response, the middleware logs the status code of the response and the time it took to process the request.

  5. Return Response: Finally, the middleware returns the response to the client.

Running the Application

To run the FastAPI application, use the following command:

Navigate to http://127.0.0.1:8000 in your browser. You will see the response {"message": "Hello, World!"}. Check your terminal to see the logged request and response details.

Summary

Middleware in FastAPI is a powerful tool to handle cross-cutting concerns such as logging, authentication, and modifying requests or responses. By defining middleware functions, you can easily intercept and process requests and responses in a centralized manner.


purpose of using middeware:

purpose of using middleware

Middleware in FastAPI is used for several purposes to handle common processing tasks for incoming requests and outgoing responses. Some of the key purposes include:

  1. Authentication and Authorization: Ensure that incoming requests have valid credentials before allowing access to endpoints.

  2. Logging: Log details about incoming requests and outgoing responses for monitoring and debugging.

  3. Rate Limiting: Limit the number of requests from a user or IP address to prevent abuse.

  4. Request/Response Modification: Modify requests before they reach the endpoints and responses before they are sent to the client.

  5. CORS (Cross-Origin Resource Sharing): Handle CORS headers to allow or restrict access from different origins.

  6. Error Handling: Centralize error handling logic to manage how errors are processed and returned to clients.

Example Purposes

Authentication and Authorization

Check if the request contains a valid API key.

Logging

Log details of each request and response.

Rate Limiting

Limit the number of requests from a user.

Summary

Middleware is a powerful tool in FastAPI that allows you to apply common processing logic across multiple endpoints. It helps keep your code clean and DRY (Don't Repeat Yourself) by centralizing tasks like authentication, logging, rate limiting, and more.

Last updated