build_middleware_stack() — fastapi Function Reference
Architecture documentation for the build_middleware_stack() function in applications.py from the fastapi codebase.
Entity Profile
Dependency Diagram
graph TD 0ad508e9_c474_fd89_127a_1e77e78303e4["build_middleware_stack()"] 587454b3_6db6_011f_9fa4_3e4e2e09b72d["FastAPI"] 0ad508e9_c474_fd89_127a_1e77e78303e4 -->|defined in| 587454b3_6db6_011f_9fa4_3e4e2e09b72d style 0ad508e9_c474_fd89_127a_1e77e78303e4 fill:#6366f1,stroke:#818cf8,color:#fff
Relationship Graph
Source Code
fastapi/applications.py lines 1001–1047
def build_middleware_stack(self) -> ASGIApp:
# Duplicate/override from Starlette to add AsyncExitStackMiddleware
# inside of ExceptionMiddleware, inside of custom user middlewares
debug = self.debug
error_handler = None
exception_handlers: dict[Any, ExceptionHandler] = {}
for key, value in self.exception_handlers.items():
if key in (500, Exception):
error_handler = value
else:
exception_handlers[key] = value
middleware = (
[Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
+ self.user_middleware
+ [
Middleware(
ExceptionMiddleware, handlers=exception_handlers, debug=debug
),
# Add FastAPI-specific AsyncExitStackMiddleware for closing files.
# Before this was also used for closing dependencies with yield but
# those now have their own AsyncExitStack, to properly support
# streaming responses while keeping compatibility with the previous
# versions (as of writing 0.117.1) that allowed doing
# except HTTPException inside a dependency with yield.
# This needs to happen after user middlewares because those create a
# new contextvars context copy by using a new AnyIO task group.
# This AsyncExitStack preserves the context for contextvars, not
# strictly necessary for closing files but it was one of the original
# intentions.
# If the AsyncExitStack lived outside of the custom middlewares and
# contextvars were set, for example in a dependency with 'yield'
# in that internal contextvars context, the values would not be
# available in the outer context of the AsyncExitStack.
# By placing the middleware and the AsyncExitStack here, inside all
# user middlewares, the same context is used.
# This is currently not needed, only for closing files, but used to be
# important when dependencies with yield were closed here.
Middleware(AsyncExitStackMiddleware),
]
)
app = self.router
for cls, args, kwargs in reversed(middleware):
app = cls(app, *args, **kwargs)
return app
Domain
Subdomains
Defined In
Source
Frequently Asked Questions
What does build_middleware_stack() do?
build_middleware_stack() is a function in the fastapi codebase, defined in fastapi/applications.py.
Where is build_middleware_stack() defined?
build_middleware_stack() is defined in fastapi/applications.py at line 1001.
Analyze Your Own Codebase
Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.
Try Supermodel Free