Middleware
A "middleware" is a function that works with every request before it is processed by any specific path operation and also with every response before returning it.
- It takes each request that comes to your application.
- It can then do something to that request or run any needed code.
- Then it passes the request to be processed by the rest of the application (by some path operation).
- It then takes the response generated by the application (by some path operation).
- It can do something to that response or run any needed code.
-
Then it returns the response.
Note: If you have dependencies with
yield
, the exit code will run after the middleware.If there were any background tasks, they will run after all the middleware.
Add Middleware(s)
To add a middleware, import it into your settings file and add it to the middleware list as a dictionary with the label "root" pointing towards your function and the keyword arguments specified later in the dict, an example is shown below
from fastapi.middleware.cors import CORSMiddleware
MIDDLEWARE = [
{
"root":CORSMiddleware,
"allow_origins":ALLOWED_ORIGINS,
"allow_credentials":ALLOW_CREDENTIALS,
"allow_methods":ALLOW_METHODS,
"allow_headers":ALLOW_HEADERS
},
]