Making Your Flask(Python) Site/API Online🌐
Tags: python, linux, ubuntu, devops
Published: 2022-03-20 12:26:15

Hi guys, In the previous [Post](https://www.thegogamicblog.xyz/making-a-rest-api-using-python-flask/) we created a REST API using Flask. Now you might be wondering **How can you make the API online**? So, In this post, we will be hosting a Flask API in a [Digital Ocean](https://www.gogamic.com/ref/do) Server

## Creating a server in Digital Ocean

So we are gonna utilize the 100$ free credit which is given for new users in Digital Ocean (note: This step is optional if you have a server in another Cloud)

These are the steps:-

Visit [Digital Ocean](https://www.gogamic.com/ref/do) and sign up for a new account if you don't have an account

1. Enter your Card Details to validate yourself as a Human.

![Making Your Flask(Python) Site/API Online🌐](https://res-3.cloudinary.com/gogamictechnologies/image/upload/q_auto/v1/ghost-blog-images/create.5e7554fead014c2002f9b2bd75739531dfe78ec3b027039d86de2c7f3b35612e.png)

2. In the create menu, click Droplets to open the Droplet create the page. If you don't have any Droplets, the Resources tab displays a large, blue Get Started with a Droplet button, which takes you to the same Droplet create the page.‌‌

![Making Your Flask(Python) Site/API Online🌐](https://res-2.cloudinary.com/gogamictechnologies/image/upload/q_auto/v1/ghost-blog-images/choose-image.6a83962611e90c5b3066c908cad05bac2a2a2d0a65a4accd4403a31a021b3519.png)

3. choose any OS/Image you like In this case I am going over Ubuntu 18.04‌‌

![Making Your Flask(Python) Site/API Online🌐](https://res-4.cloudinary.com/gogamictechnologies/image/upload/q_auto/v1/ghost-blog-images/choose-a-plan.5ae754c26c33ee70abf765de85ff117c11aa97577cff6201830e1a11841d7c67.png)

4. Choose the plan that best suits your needs In this case I am gonna go with the 18$ plan.

![Making Your Flask(Python) Site/API Online🌐](https://res-5.cloudinary.com/gogamictechnologies/image/upload/q_auto/v1/ghost-blog-images/futurama-processing.gif)
_Takes Time⏳_

- Your Droplet will be created!
- If you would like to learn about SSH do read this [Post](https://www.digitalocean.com/docs/droplets/how-to/connect-with-ssh/).

## Creating a basic flask app

Run this code `pip install gunicorn flask`

This is a minimal flask app and I will name it wsgi.py you can name the file anything you prefer

{% gist https://gist.github.com/raghavmri/660e522ee0bd60d6a26688002309f4ce %}

- You can test the configuration by running `gunicorn --bind 0.0.0.0:8000 wsgi`
- If you want to create a Rest API using Flask do check out this [Post](https://www.thegogamicblog.xyz/making-a-rest-api-using-python-flask/)

## The Gurnicorn Configuration

SSH onto your server run `sudo nano /etc/systemd/system/myproject.service` to open the configuration file for your project

That brings in an editor to your terminal and write the following(edit as per your need)

```
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target

[Service]
User=user
Group=nginx
WorkingDirectory=/home/user/myproject
Environment="PATH=/home/user/myproject/myprojectenv/bin"
ExecStart=/home/user/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi

[Install]
WantedBy=multi-user.target 
```

- Then press crtl+c to save it and crtl+x to exit the editor
- Run `sudo systemctl start myproject` & `sudo systemctl enable myproject`
- You can check the status of your application by running `sudo systemctl status myproject`

## Configuring Nginx to proxy the requests

1. Run `sudo apt update sudo && sudo apt-get install nginx` to update any outdated software and install Nginx

2. Once Nginx is installed, You can edit your configuration file by `sudo nano /etc/nginx/sites-available/myproject`

3. Then paste the following code to your configuration file

```
server {
    listen 80;
    server_name your_domain www.your_domain;

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
    }
}
```

- The above code instructs Nginx to proxy your request to the sock file that we created earlier
- To link your project to Nginx sites run  `sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled`
- Run this code to Test your Configuration `sudo nginx -t`
- Then run this to restart Nginx `sudo systemctl restart nginx`
- If you have enabled UFW then run  `sudo ufw allow 'Nginx Full'`
- Visit `http://yourip` and your app should  be live now

## Securing your app with an SSL

1. Run `sudo add-apt-repository ppa:certbot/certbot sudo apt install python-certbot-nginx` to install [certbot](https://certbot.eff.org/)  and Nginx certbot plugin onto your server
2. Run `sudo certbot --nginx -d your_domain -d www.your_domain --agree-tos -m your_name@yourdomain.com` to get a new certificated from certbot
3. You may get a similar output to this 👇

```
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
```

4. Select the option of your choice

5. You will get an output like this

```
IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/your_domain/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/your_domain/privkey.pem
   Your cert will expire on 2018-07-23. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
   Donating to EFF: https://eff.org/donate-le
```

- (optional) Run `sudo ufw delete allow 'Nginx HTTP'` to disable HTTP in UFW
- Try visiting `https://your IP or Your domain` and Your site should be secured🔒
<a href="https://www.buymeacoffee.com/raghavmri"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a pizza&emoji=🍕&slug=raghavmri&button_colour=5F7FFF&font_colour=ffffff&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00" /></a>