본문으로 건너뛰기

FastAPI Middleware

호출 순서

미들웨어 호출 순서는 FastAPI.user_middleware에 들어있는 순서대로 실행됩니다.

  1. 인스턴스 생성 시 설정한 middlewareFastAPI.user_middleware의 기본값으로 설정됩니다.
  2. FastAPI.add_middleware 또는 @FastAPI.middleware 실행 시 FastAPI.user_middleware의 맨 앞에 미들웨어를 추가합니다.
  3. 모든 설정이 완료된 후 ServerErrorMiddleware -> FastAPI.user_middleware -> ExceptionMiddleware 순으로 미들웨어가 설정됩니다.
from fastapi import FastAPI, Request, Response
from fastapi.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint


async def middleware1(request: Request, call_next: RequestResponseEndpoint) -> Response:
print("Middleware 1")
response = await call_next(request)
print("Middleware 1")
return response

async def middleware2(request: Request, call_next: RequestResponseEndpoint) -> Response:
print("Middleware 2")
response = await call_next(request)
print("Middleware 2")
return response

app = FastAPI(
middleware=[
Middleware(BaseHTTPMiddleware, dispatch=middleware1),
]
)

app.add_middleware(BaseHTTPMiddleware, dispatch=middleware2)

@app.middleware("http")
async def middleware3(request: Request, call_next: RequestResponseEndpoint) -> Response:
print("Middleware 3")
response = await call_next(request)
print("Middleware 3")
return response
Middleware 3
Middleware 2
Middleware 1
Middleware 1
Middleware 2
Middleware 3