Home / Function/ middleware() — fastapi Function Reference

middleware() — fastapi Function Reference

Architecture documentation for the middleware() function in applications.py from the fastapi codebase.

Entity Profile

Dependency Diagram

graph TD
  89fd320c_1f30_8e12_50ce_3b00717ad9eb["middleware()"]
  587454b3_6db6_011f_9fa4_3e4e2e09b72d["FastAPI"]
  89fd320c_1f30_8e12_50ce_3b00717ad9eb -->|defined in| 587454b3_6db6_011f_9fa4_3e4e2e09b72d
  style 89fd320c_1f30_8e12_50ce_3b00717ad9eb fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

fastapi/applications.py lines 4581–4625

    def middleware(
        self,
        middleware_type: Annotated[
            str,
            Doc(
                """
                The type of middleware. Currently only supports `http`.
                """
            ),
        ],
    ) -> Callable[[DecoratedCallable], DecoratedCallable]:
        """
        Add a middleware to the application.

        Read more about it in the
        [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).

        ## Example

        ```python
        import time
        from typing import Awaitable, Callable

        from fastapi import FastAPI, Request, Response

        app = FastAPI()


        @app.middleware("http")
        async def add_process_time_header(
            request: Request, call_next: Callable[[Request], Awaitable[Response]]
        ) -> Response:
            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
        ```
        """

        def decorator(func: DecoratedCallable) -> DecoratedCallable:
            self.add_middleware(BaseHTTPMiddleware, dispatch=func)
            return func

        return decorator

Domain

Subdomains

Frequently Asked Questions

What does middleware() do?
middleware() is a function in the fastapi codebase, defined in fastapi/applications.py.
Where is middleware() defined?
middleware() is defined in fastapi/applications.py at line 4581.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free