How to Use Trusted Host Middleware in FastAPI
In FastAPI, use
TrustedHostMiddleware from starlette.middleware.trustedhost to restrict requests to specific hostnames. Add it to your app with allowed hosts as a list, e.g., ["example.com", "localhost"], to block unwanted hosts and improve security.Syntax
The TrustedHostMiddleware is added to a FastAPI app to allow only requests from specified hostnames. You import it from starlette.middleware.trustedhost and add it using app.add_middleware().
Key parts:
allowed_hosts: a list of hostnames or patterns to accept.app.add_middleware(): method to add middleware to FastAPI.
python
from fastapi import FastAPI from starlette.middleware.trustedhost import TrustedHostMiddleware app = FastAPI() app.add_middleware( TrustedHostMiddleware, allowed_hosts=["example.com", "localhost", "127.0.0.1"] )
Example
This example shows a FastAPI app that only accepts requests from localhost and 127.0.0.1. Requests from other hosts will get a 400 error.
python
from fastapi import FastAPI from starlette.middleware.trustedhost import TrustedHostMiddleware from fastapi.responses import PlainTextResponse app = FastAPI() app.add_middleware( TrustedHostMiddleware, allowed_hosts=["localhost", "127.0.0.1"] ) @app.get("/") async def read_root(): return {"message": "Hello from trusted host!"}
Output
When accessed from allowed hosts (localhost or 127.0.0.1):
{"message": "Hello from trusted host!"}
When accessed from disallowed hosts:
400 Bad Request - Invalid host header
Common Pitfalls
- Not including all needed hosts in
allowed_hostscauses valid requests to be blocked. - Using wildcards incorrectly; use
"*.example.com"to allow subdomains. - For local development, remember to include
localhostand127.0.0.1. - Middleware order matters; add
TrustedHostMiddlewareearly.
python
from fastapi import FastAPI from starlette.middleware.trustedhost import TrustedHostMiddleware app = FastAPI() # Wrong: missing localhost, will block local requests app.add_middleware( TrustedHostMiddleware, allowed_hosts=["example.com"] ) # Correct: include localhost and subdomains app.add_middleware( TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com", "localhost", "127.0.0.1"] )
Quick Reference
- Import:
from starlette.middleware.trustedhost import TrustedHostMiddleware - Add middleware:
app.add_middleware(TrustedHostMiddleware, allowed_hosts=[...]) - Allowed hosts: List hostnames or patterns like
"*.example.com" - Errors: Requests from disallowed hosts return 400 Bad Request
Key Takeaways
Use TrustedHostMiddleware to restrict allowed hostnames and improve security.
Always include all valid hosts your app will receive requests from, including localhost for development.
Use wildcard patterns like "*.example.com" to allow subdomains.
Requests from disallowed hosts return a 400 Bad Request error automatically.
Add TrustedHostMiddleware early in your app setup to ensure proper request filtering.