What is middleware, and how can you deactivate it for a specific route in FastAPI?|

Fast Api

What is middleware, and how can you deactivate it for a specific route in FastAPI?

What is middleware?

A “middleware” function is one that works with each request before it is processed by any path operation. Also, for each response before returning it.

How to create a middleware?

To create a middleware you use the decorator @app.middleware("http") on top of a function.

The middleware function is given the following:

import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

You can use it before and after the response.

You can add code to be run with the request, before any path operation receives it.

import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

You can disable middleware on a particular route by simply checking the route url in the request.

For example:

import time

from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    if request.url.path == "/some_path_to_disable_middleware":
        # If the request path matches the one you want to exclude,
        # don't run the middleware and proceed directly to the route handler.
        response = await call_next(request)
    else:
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
    return response

Here this code is important:

if request.url.path == "/some_path_to_disable_middleware":
    # If the request path matches the one you want to exclude,
    # don't run the middleware and proceed directly to the route handler.
    response = await call_next(request)

Follow me for more such blog also clap if you like this one.