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).
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.