But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares handle server errors and custom exception handlers work properly.
For that, you use app.add_middleware() (as in the example for CORS).
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.
allowed_hosts - 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 use allowed_hosts=["*"] or omit the middleware.
If an incoming request does not validate correctly then a 400 response will be sent.
minimum_size - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to 500.
compresslevel - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to 9. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes.