Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Middleware

You can add middleware toFastAPI applications.

A "middleware" is a function that works with everyrequest before it is processed by any specificpath operation. And also with everyresponse before returning it.

  • It takes eachrequest that comes to your application.
  • It can then do something to thatrequest or run any needed code.
  • Then it passes therequest to be processed by the rest of the application (by somepath operation).
  • It then takes theresponse generated by the application (by somepath operation).
  • It can do something to thatresponse or run any needed code.
  • Then it returns theresponse.

Technical Details

If you have dependencies withyield, the exit code will runafter the middleware.

If there were any background tasks (covered in theBackground Tasks section, you will see it later), they will runafter all the middleware.

Create a middleware

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

The middleware function receives:

  • Therequest.
  • A functioncall_next that will receive therequest as a parameter.
    • This function will pass therequest to the correspondingpath operation.
    • Then it returns theresponse generated by the correspondingpath operation.
  • You can then further modify theresponse before returning it.
importtimefromfastapiimportFastAPI,Requestapp=FastAPI()@app.middleware("http")asyncdefadd_process_time_header(request:Request,call_next):start_time=time.perf_counter()response=awaitcall_next(request)process_time=time.perf_counter()-start_timeresponse.headers["X-Process-Time"]=str(process_time)returnresponse

Tip

Keep in mind that custom proprietary headers can be addedusing theX- prefix.

But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (CORS (Cross-Origin Resource Sharing)) using the parameterexpose_headers documented inStarlette's CORS docs.

Technical Details

You could also usefrom starlette.requests import Request.

FastAPI provides it as a convenience for you, the developer. But it comes directly from Starlette.

Before and after theresponse

You can add code to be run with therequest, before anypath operation receives it.

And also after theresponse is generated, before returning it.

For example, you could add a custom headerX-Process-Time containing the time in seconds that it took to process the request and generate a response:

importtimefromfastapiimportFastAPI,Requestapp=FastAPI()@app.middleware("http")asyncdefadd_process_time_header(request:Request,call_next):start_time=time.perf_counter()response=awaitcall_next(request)process_time=time.perf_counter()-start_timeresponse.headers["X-Process-Time"]=str(process_time)returnresponse

Tip

Here we usetime.perf_counter() instead oftime.time() because it can be more precise for these use cases. 🤓

Multiple middleware execution order

When you add multiple middlewares using either@app.middleware() decorator orapp.add_middleware() method, each new middleware wraps the application, forming a stack. The last middleware added is theoutermost, and the first is theinnermost.

On the request path, theoutermost middleware runs first.

On the response path, it runs last.

For example:

app.add_middleware(MiddlewareA)app.add_middleware(MiddlewareB)

This results in the following execution order:

  • Request: MiddlewareB → MiddlewareA → route

  • Response: route → MiddlewareA → MiddlewareB

This stacking behavior ensures that middlewares are executed in a predictable and controllable order.

Other middlewares

You can later read more about other middlewares in theAdvanced User Guide: Advanced Middleware.

You will read about how to handleCORS with a middleware in the next section.


[8]ページ先頭

©2009-2026 Movatter.jp