Great! I'll demonstrate three approaches for serving FastAPI over HTTPS with code examples:
- Using
uvicorn with SSL certificates (inline with previous example)
- Using
hypercorn to run HTTPS FastAPI server
- Using Nginx as a reverse proxy handling HTTPS (for production setups)
1. Using Uvicorn with SSL
app.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello over HTTPS with Uvicorn!"}
Generate self-signed cert and key (for local testing):
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 365
Run:
uvicorn app:app --host 0.0.0.0 --port 8443 --ssl-keyfile=key.pem --ssl-certfile=cert.pem
Access:
https://localhost:8443/
2. Using Hypercorn (alternative ASGI server supporting SSL)
First install hypercorn if you don’t have it:
pip install hypercorn
Run the same app.py, then launch:
hypercorn app:app -b 0.0.0.0:8443 --certfile cert.pem --keyfile key.pem
Access:
https://localhost:8443/
3. Using Nginx as HTTPS Reverse Proxy (recommended production approach)
Why use reverse proxy?
- Your FastAPI app runs plain HTTP on localhost or internal port
- Nginx handles SSL, caching, compression, etc.
- Nginx exposes HTTPS to clients
Example Nginx config snippet
server {
listen 443 ssl;
server_name your-domain.com;
ssl_certificate /etc/ssl/certs/your_cert.pem;
ssl_certificate_key /etc/ssl/private/your_key.pem;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
In this setup, run your app without SSL:
uvicorn app:app --host 127.0.0.1 --port 8000
Then Nginx serves HTTPS externally.
Summary
| Approach | Pros | Cons |
|---|
| Uvicorn SSL | Simple to set up, quick for testing | Not recommended for prod HTTPS |
| Hypercorn SSL | Another SSL-capable ASGI server | Same as above |
| Nginx Reverse Proxy | Robust, production-grade, scalable | Needs extra config and setup |
If you want, I can help you automate cert generation with Let's Encrypt or show a full Docker example with HTTPS — just ask!