Enable HTTPS in FastAPI (Uvicorn)

You need SSL certificate private key in .env
 
HOST=0.0.0.0
PORT=8443
SSL_CRT=D:\certs\server.crt
SSL_KEY=D:\certs\server.key
Command to run FastAPI with SSL:
 
python -B -m uvicorn app.main:app --host 0.0.0.0 --port 8443 --ssl-keyfile "%SSL_KEY%" --ssl-certfile "%SSL_CRT%"
If not found error (just for testing, add paths):
 
python -B -m uvicorn app.main:app --host 0.0.0.0 --port 8443 --ssl-keyfile "D:\certs\server.key"  --ssl-certfile "D:\certs\server.crt"

Programmatic start

For a programmatic start with uvicorn.run() create a small server.py that: - Loads environment variables (from .env or system) - Builds an SSLContext - Starts Uvicorn programmatically app/server.py
 
"""
    python -B run_server.py
"""

import os
import ssl
import uvicorn

from dotenv import load_dotenv
load_dotenv()

HOST = os.getenv("HOST", "0.0.0.0")
PORT = int(os.getenv("PORT", "8443"))

SSL_CERT = os.getenv("SSL_CRT")
SSL_KEY  = os.getenv("SSL_KEY")

if __name__ == "__main__":
    uvicorn.run("app.main:app", host=HOST, port=PORT, 
    ssl_certfile=SSL_CERT,
    ssl_keyfile=SSL_KEY
)