Adding SSL to FastAPI

Adding SSL to FastAPI

Secure Socket Layer (SSL) is essential for encrypting data transmitted between your application and its users. In this guide, we’ll walk you through how to add SSL to your FastAPI application, ensuring secure communication and compliance with modern web standards.


Why SSL is Important

SSL ensures:

  • Data Security: Encrypts communication to prevent data interception.
  • Authentication: Verifies the server’s identity to users.
  • SEO Benefits: Search engines prioritize HTTPS websites.
  • User Trust: Displays a secure padlock in browsers, improving user confidence.


Steps to Add SSL to a FastAPI Application

Prerequisites

  1. FastAPI Application: A working FastAPI application.
  2. Domain Name: SSL certificates require a domain name.
  3. Certificate Authority (CA): Obtain an SSL certificate from a trusted CA (e.g., Let’s Encrypt, DigiCert).
  4. Tools: Install OpenSSL for generating and managing certificates.


Step 1: Obtain an SSL Certificate

Using Let’s Encrypt (Free SSL Certificates)

Let’s Encrypt provides free SSL certificates. Use the Certbot tool to generate a certificate.

Install Certbot:

sudo apt update
sudo apt install certbot
sudo apt install python3-certbot-nginx  # For NGINX users        

Generate a Certificate:

sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com        

Locate the Certificate Files: Certificates are typically stored in:

/etc/letsencrypt/live/yourdomain.com/fullchain.pem
/etc/letsencrypt/live/yourdomain.com/privkey.pem        

ep 2: Configure SSL in FastAPI

FastAPI doesn’t directly handle SSL termination. Instead, you can use:

  1. Direct Integration (using Hypercorn or Uvicorn)
  2. Reverse Proxy (using NGINX)


Option 1: Direct Integration with Uvicorn

Install Uvicorn:

pip install uvicorn        

Update Your FastAPI Application:

import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Welcome to the SSL-enabled FastAPI app!"}

if __name__ == "__main__":
    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=443,
        ssl_certfile="/path/to/fullchain.pem",
        ssl_keyfile="/path/to/privkey.pem"
    )        

Run the Application:

python app.py        

Your FastAPI app is now accessible via HTTPS.


Option 2: Using NGINX as a Reverse Proxy

Install NGINX:

sudo apt update
sudo apt install nginx        

Configure NGINX: Edit the configuration file:

sudo nano /etc/nginx/sites-available/fastapi        

Add the following:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}        

Enable the Configuration:

sudo ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled
sudo nginx -t  # Test the configuration
sudo systemctl restart nginx        

Start Your FastAPI Application:

uvicorn app:app --host 0.0.0.0 --port 8000        

Now, NGINX will handle SSL termination and forward requests to your FastAPI app.


Step 3: Test Your Setup

Open your browser and navigate to:

https://yourdomain.com        

Verify the SSL padlock icon in the address bar.


Automating SSL Renewal

Let’s Encrypt certificates expire every 90 days. Automate renewal using Certbot:

Test Renewal:

sudo certbot renew --dry-run        

Add a Cron Job:

sudo crontab -e        

Add the following line:

0 0 * * * certbot renew --quiet        

This will renew your certificates automatically.


Best Practices

  • Redirect HTTP to HTTPS: Always redirect traffic from port 80 to 443.
  • Use Strong Cipher Suites: Ensure your NGINX configuration uses secure ciphers.
  • Monitor SSL Expiry: Use tools like SSL Labs to monitor certificate expiration.


Conclusion

Adding SSL to your FastAPI application enhances security, builds user trust, and ensures compliance with modern web standards. Whether you use Uvicorn directly or leverage NGINX as a reverse proxy, this guide provides the steps to secure your application effectively.

Thank you for taking the time to read! Follow me for more insights and updates, and let’s continue to grow and learn together.















Thank you for this post. I have a problem trying the uvicorn solution: the letsencrypt pem files are inaccessible as they are owned by root. Suggestions on how to get around this? Using sudo causes other problems with the code. Thanks, George

Like
Reply

Great guide! SSL is crucial for secure communication and this is a must-read for developers working with FastAPI.

Like
Reply

To view or add a comment, sign in

More articles by Manikandan Parasuraman

Others also viewed

Explore content categories