How To Deploy Your FastAPI Application on Amazon EC2, and Activate SSL.
Published: 2024-03-20 15:36:54

Hi there, welcome back. In the last troubleshooting article, we talked about [How To Convert PPTX file to PDF using Python on Windows, Mac, or Linux](https://dev.to/ephraimx/how-to-convert-pptx-file-to-pdf-using-python-on-windows-mac-or-linux-20ij). In case you missed it, I began a troubleshooting series where I write articles on problems I have encountered while building products, and provide the solutions that I employed to solve the problem. In this article, as you have read from the title, we will consider how to build and deploy a FastAPI application on Amazon Elastic Compute Cloud, usually referred to as Amazon EC2, and also activate SSL security for the application.

To follow along with this article, it'll be nice if you have a bit of familiarity with Python, FastAPI, and AWS, but if not, no worries, I'll try to make it as understandable and relatable as possible, but you'll need to have a basic Python foundation. Alright, lots of talk, let's get started.

## The Backstory

As with the previous and upcoming troubleshooting articles, there will be a backstory, and the story here is sometime last year I was building a couple of APIs to be consumed by a React application, after building the APIs, I went ahead to implement it on the front-end, only to be met with an error relating to the API not having SSL enabled on it, so essentially, it wasn't safe for my front-end application to react, rather interact with it.

After some digging, and a couple of trials and errors, I found the solution in this YouTube video, and decided to share it with you🫵.

## Solution 🥁🥁🥁.

To follow through with this solution, it is expected that you have some familiarity with AWS, and also Python. With that being said, let's begin.

### Step  1: Log In To Your AWS Account

Go to https://console.aws.amazon.com/, and put in your login details. There are two types of users in AWS, root users and IAM users. If you are a root user, your email address and password will be sufficient. If you are an IAM user, you will require your account ID, username, and password.


![Log In To Your AWS Account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51lh83vljd4uty10jvfb.png)

### Step 2: Create An EC2 Instance

- To create an EC2 instance, go to the search bar on the home console and search "EC2" and select the service.

![Create EC2 Instance](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1ov25ez1aijz0804qpk.png)

- Next, click on Launch Instance. If you don't see the Launch Instance button, select "Instances" on the left-hand side, and then on the top right-hand of the page, click on "Launch Instance".


![Launch Instance](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jw64l56j669o5vdglwd6.png)

- Next, fill in the details that you want your instance to be associated with. The following details will be used for this article:
    - Name: fastapi-ec2-ssl
    - Amazon Machine Image: Ubuntu
    - Instance Type: t2.micro
    - Key Pair Login: ****(You'll have to create yours if you it's not present)
    - Network Settings: Allow HTTP and HTTPS traffic from the internet

- Finally, cross-check the details above and select Launch Instance at the bottom of the page.

![Fill In EC2 Details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b78p0qr04uw3aphqmu69.png)

### Step 3: Log in to your EC2 Instance via SSH

- Next, head back to the instances page, select the checkbox of the newly created instance, and click the connect button and the top of the page.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/53eyk7gjt5tfu2v3nnnj.png)

- Select the method with which you would want to connect, for this article, we'll use the `SSH client` method.

- Once selected, copy the example code and paste it into your terminal. Keep in mind that the directory of the terminal should point to the location where your key pair is present.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hlkejlmjsfbo53ihh2v.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4uwfsbofbghju7rgwpm.png)

Now we can begin!

### Step 4: Link Your EC2 IPV4 Address With Your Route 53 Domain

To go through with this step you need to set up a domain on Route 53, if you don't know how to go through with that kindly refer to this [article](https://towardsaws.com/how-to-add-a-domain-with-amazon-route-53-fc4452fa2b60) to set up a custom domain on AWS.

Done? Go back to your EC2 instance and grab your public IPV4 address. 

![EC2 IPV4 ADDRESS](https://imgur.com/9QBMtTm.jpeg)

Now head over to the hosted zone created in your Route 53 directory, and click on it.

![Route 53 directory](https://imgur.com/ygvID5u.jpeg)

Next create two records, for the first record leave the name field blank, place the IP address in the value field, and select the Create Record button. For the second record, place the `www.` prefix in the namespace, place again the IP address in the value field, and select the Create Record button as done previously.

![Record One](https://imgur.com/FUjv1he.jpeg)

![Record Two](https://imgur.com/2dUYDpu.jpeg)

PS: In my example above, I had to create a sub-domain as I already have a functioning API on the main domain.

### Step 5: Install and Update Needed Packages.

Now we can begin to install the libraries we'll use, which include Python and Apache2.

- First run `sudo apt-get update -y` to update the packages in the local repository.
- Next, run `sudo apt install -y python3 python3-pip` to install Python 3 and pip.
- Next, run `sudo apt-get install -y apache2` to install Apache 2 which will be used to serve the APIs to users.

### Step 6: Install Certbot and Configure SSL

What is Certbot? In case you've not heard of it...

> Certbot is a free, open-source software tool for automatically using Let’s Encrypt certificates on manually administrated websites to enable HTTPS. 

> Certbot is made by the Electronic Frontier Foundation (EFF), a 501(c)3 nonprofit based in San Francisco, CA, that defends digital privacy, free speech, and innovation. - https://certbot.eff.org/

To install Certbot:

- Run `sudo apt install certbot python3-certbot-apache`.
- Next, run `sudo certbot --apache -d your_domain.com` where "your_domain.com" represents the domain name that you attached to your public IPV4 address. At this stage, the EFF will request your email, if you wish to agree to the terms of service (say yes), and if you would like to receive promotional emails (you could say yes, or no).

To configure SSL on your server:
- Navigate to the site available directory using the command `
cd /etc/apache2/sites-available/`
- Next, edit the configuration file. To do this, run `sudo nano 000-default-le-ssl.conf`
- In the file opened, scroll to the bottom, just before the line with ServerName, and paste the following: 
```
ProxyPass / http://127.0.0.1:8000/ 
ProxyPassReverse / http://127.0.0.1:8000/
```

ProxyPass allows you to map specific URLs or URL patterns to the backend service. So essentially when you request the URL it maps you to FastAPI backend service.

- Next, enable proxy modules by running the following commands
```
sudo a2enmod proxy
sudo a2enmod proxy_http
```

- To wrap this section, restart the Apache service.
```
sudo systemctl restart apache2
```

### Step 7: Set Up Your FastAPI Application

Next, set up your FastAPI application on the EC2 server. To begin, install FastAPI and Uvicorn.

```
pip install fastapi uvicorn["standard"]
```

Next, create the `main.py` file to

```
sudo touch main.py
```

Then, open the file and paste the following code that will send a JSON message when a get request is sent to the index page.

To open the file:

```
sudo nano main.py
```


```
from fastapi import FastAPI


@app.get("/")
def read_root():
    return {"message": "Hello World"}
```

Save the file (Ctrl/Cmd + S) and Close the file (Ctrl/Cmd + X).

### Final Step: Start the Application

To confirm that the SSL is activated, start the FastAPI application.

```
nohup uvicorn main:app --host 127.0.0.1 --port 8000 &
```

We use the nohup command to ensure that the process is still running even after you exit the shell.

Head to your browser, and paste the code in the browser, and you'll see a padlock icon indicating that the site is activated with SSL.

![](https://imgur.com/O4TtAEE.jpeg)


## And It's A Wrap🎉

This article covers how to activate SSL on an EC2 instance for a FastAPI application. It details how to set up an EC2 instance, install the necessary packages, activate SSL on the Apache server, and start the FastAPI application.

If you're still getting started with FastAPI you can refer to this [video by Digital Ocean](https://www.digitalocean.com/community/tech-talks/getting-started-with-python-fastapi) to learn more about the technology.