English 中文(简体)
FastAPI - Middleware
  • 时间:2024-11-03

FastAPI - Middleware


Previous Page Next Page  

A middleware is a function that is processed with every request (before being processed by any specific path operation) as well as with every response before returning it. This function takes each request that comes to your apppcation. It may perform some process with the request by running a code defined in it and then passes the request to be processed by the corresponding operation function. It can also process the response generated by the operation function before returning it.

Following are some of the middleware available in FastAPI pbrary −

    CORSMiddleware

    HTTPSRedirectMiddleware

    TrustedHostMiddleware

    GZipMiddleware

FastAPI provides app.add_middleware() function to handle server errors and custom exception handlers. In addition to the above integrated middleware, it is possible to define a custom middleware. The following example defines the addmiddleware() function and decorates it into a middleware by decorating it with @app.middleware() decorator

The function has two parameters, the HTTP request object, and the call_next() function that will send the API request to its corresponding path and return a response.

In addition to the middleware function, the apppcation also has two operation functions.


import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def addmiddleware(request: Request, call_next):
   print("Middleware works!")
   response = await call_next(request)
   return response
@app.get("/")
async def index():
   return {"message":"Hello World"}
@app.get("/{name}")
async def hello(name:str):
   return {"message":"Hello "+name}

As the apppcation runs, for each request made by the browser, the middleware output (Middleware works!) will appear in the console log before the response output.

Advertisements