Understanding Proxy Scenarios
Reverse proxies sit between clients and your FastAPI application:- Terminate SSL/TLS (serve HTTPS while talking to your app over HTTP)
- Add a path prefix (serve your app at
/api/v1instead of/) - Forward headers about the original request
Without proper configuration, your FastAPI app won’t know about the original request’s protocol, host, or path.
Root Path
When your app is mounted at a path prefix, use theroot_path parameter:
Reading Root Path from Request
Setting Root Path in Application
/api/v1/app instead of just /app.
Configuring with Servers
Define alternative server URLs in the OpenAPI schema:- Shows multiple server options in the docs
- Sets the path prefix to
/api/v1 - Allows users to test against different environments
Controlling Root Path in Servers
By default,root_path is included in server URLs. To disable this:
Nginx Configuration
Basic Proxy Setup
Proxy with Path Prefix
SSL Termination
Traefik Configuration
Environment-Based Configuration
Setroot_path from environment variables:
Docker and Kubernetes
Docker Compose with Nginx
Kubernetes Ingress
Forwarded Headers
Access proxy forwarded headers in your application:Testing Proxy Configuration
Test your configuration locally:Common Pitfalls
Incorrect OpenAPI Schema URLs
If docs aren’t loading, check theroot_path:
Mixed HTTP/HTTPS
Ensure proxies setX-Forwarded-Proto correctly:
Missing Host Headers
Best Practices
- Always set
root_pathwhen behind a proxy with a path prefix - Configure proxies to forward
X-Forwarded-*headers - Use environment variables for deployment-specific configuration
- Test OpenAPI docs to verify proxy configuration
- Implement proper logging to track the original client IP
- Use SSL/TLS termination at the proxy for better performance
- Validate forwarded headers come from trusted sources
Health Checks
Configure health check endpoints for load balancers:See Also
- Custom Middleware - Create custom middleware
- CORS - Configure cross-origin requests
- Deployment - Deploy FastAPI applications
- Security - Security best practices