Advanced Middleware
The current page still doesn’t have a translation for this language.
But you can help translating it: Contributing.
In the main tutorial you read how to add to your application.
And then you also read how to handle CORS with the CORSMiddleware.
In this section we’ll see how to use other middlewares.
As FastAPI is based on Starlette and implements the ASGI specification, you can use any ASGI middleware.
A middleware doesn’t have to be made for FastAPI or Starlette to work, as long as it follows the ASGI spec.
In general, ASGI middlewares are classes that expect to receive an ASGI app as the first argument.
But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares to handle server errors and custom exception handlers work properly.
For that, you use app.add_middleware()
(as in the example for CORS).
app.add_middleware()
receives a middleware class as the first argument and any additional arguments to be passed to the middleware.
Integrated middlewares
FastAPI includes several middlewares for common use cases, we’ll see next how to use them.
Technical Details
For the next examples, you could also use from starlette.middleware.something import SomethingMiddleware
.
FastAPI provides several middlewares in fastapi.middleware
just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.
Enforces that all incoming requests must either be https
or wss
.
TrustedHostMiddleware
Enforces that all incoming requests have a correctly set Host
header, in order to guard against HTTP Host Header attacks.
The following arguments are supported:
- - A list of domain names that should be allowed as hostnames. Wildcard domains such as
*.example.com
are supported for matching subdomains to allow any hostname either useallowed_hosts=["*"]
or omit the middleware.
If an incoming request does not validate correctly then a 400
response will be sent.
Handles GZip responses for any request that includes "gzip"
in the Accept-Encoding
header.
The middleware will handle both standard and streaming responses.
The following arguments are supported:
Other middlewares
There are many other ASGI middlewares.
For example: