Deploy your flask app on Heroku
Tags: flask, heroku, api
Published: 2022-09-18 19:57:55

Heroku is a container based cloud platform as a service (PaaS) which is used for deploying your applications on the web. It received interest in recent years due to its simple setup and budget friendly pricing. Flask is a python based web application framework used to create APIs. Its simplicity makes it the default choice for building small APIs.

In this article, we will learn to create a simple flask application and deploy it on Heroku.

## Getting Started
### Prerequisites
- [python 3.8](https://www.python.org/downloads/)
- [heroku cli](https://devcenter.heroku.com/articles/heroku-cli)
- [git](https://git-scm.com/downloads)
- [postman](https://www.postman.com/downloads/)
Download the above software from the official site. Install them on your machine. Don’t forget to select the “add to path” option while installing python.

Verify the software installation version by the following command

```
python --version
heroku --version
git --version
```

### Install dependencies
- **[virtual environment](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/)** — It is used to manage the package installation in the machine and avoid the global installation of packages. Use the following command to install it on your machine,
python -m pip install --user virtualenv
- Create a virtual environment for our project using the following command

```
python -m venv venv
```
- Activate the virtual environment using the following command
- In Windows machines,

```
venv\Scripts\activate
```
- In Linux machines,

```
venv/bin/activate
```
- **[flask](https://flask.palletsprojects.com/en/2.2.x/)** — It is a python based web application framework. Use the following command to install it on your machine,

```
pip install flask
```
- **[gunicorn](https://flask.palletsprojects.com/en/2.2.x/deploying/gunicorn/)** — It is a pure Python WSGI server. Heroku requires gunicorn to deploy the flask app on the container. Use the following command to install it on your machine,

```
pip install gunicorn
```
![version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3pydg3kljsl5zkzrfed5.PNG)

![venv](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2uaq52tcx7urvvu4prmy.PNG)
![flask](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rwqvg1y3jn0uxp8h0iix.PNG)
![gunicorn](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ai9vjdaxj2muz2tctb3u.PNG)
### Create a flask app
Flask is a small and lightweight python framework used for creating web applications.

- Create a file, `app.py` and add the following code to it.

```
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
    return '''<h1>Hello World</h1>'''
@app.route("/login",  methods = ['POST'])
def convert():
    user = request.get_json()
    if(user['username'] == 'admin' and user['password'] == '1234'):
        return jsonify({'success': True, 'message': 'Valid user'})
    return jsonify({'success': False, 'message': 'Invalid user'})
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)
```
**Understand the code,**

- Import the `flask` library, `request` and `jsonify` methods to get api request information in the json format.
- Create a flask app using `flask.Flask(__name__)`
- Create a default get route (‘/’) and return a Hello World header text as the response.
- Create a `/login` route to get user information and return a json response which contains success and message values.
- Run the server on 5000 port using `app.run(host=”0.0.0.0", port=5000)`

### Run the app
Start your basic flask server using the following command

```
python app.py
```

![run the app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojgssd87t7bhxvbhynnp.PNG)
You can see two URLs in the terminal if the server is up and running.

To test our apis,

- Open any browser and type any of the URL which is listed on the terminal.

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gvl3pgabjtg6i8poxm5.PNG)
- Open postman and select the POST option. Type http://127.0.0.1:5000/login in the input box and provide username and password in json format in the body.

![output 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2d32kfzn2cmrmxsg7uon.PNG)

### Create Heroku configuration files
Heroku requires some specific files in the directory while hosting the flask app on the cloud.

- `requirements.txt` — It contains a list of the package names and the corresponding versions that are used in the project. Create requirements.txt file using the following command.

```
pip freeze > requirements.txt
```
- `.gitignore` — It contains a list of untracked files and directories that Git should ignore. Create .gitignore file using the following command.

```
echo venv/ > .gitignore
```
- `Procfile` — It specifies the commands that are executed by the app on startup. Create Procfile using the following command.

```
echo web: gunicorn app:app > Procfile

```
![config](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u0fi4uffq0ka4h53vhp8.PNG)

### Deploy the app
We have completed the basic flask api creation and the heroku specific file creation. Now, we can deploy the app on heroku.

- Login to the Heroku account in the browser. Create a Heroku account from the link https://signup.heroku.com if you don’t have one.
- Click on New → Create new app from the dashboard.

![heroku 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4s8dn0ilc4365hwss49m.png)
- Provide a valid app name and click on Create app button to create the app. Leave the region and pipeline option as default.

![heroku 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ys7royqotxwl6sklixa7.png)
- Login to the heroku cli using the following command

```
heroku login
```
![heroku login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bs358ng9eutc1xybej8u.PNG)
- Execute the commands listed on the Deploy tab to deploy your flask app on the Heroku cloud. Skip the cd command if you are already on the app root folder.

```
git init
heroku git:remote -a flask-server-v1
git add .
git commit -am "make it better"
git push heroku master
```
`heroku git:remote -a flask-server-v1` may change according to your flask app name.

![heroku hosting 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z5t0ap23uz9cgxk85ap5.PNG)
![heroku hosting 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r60fscpl6uog1fja8rlk.PNG)

You will get a message as **https://flask-server-v1.herokuapp.com/ deployed to Heroku**, if the deployment is successful.

Instead of 127.0.0.1 you can use the host address given in the message to access the apis.

Great! Your flask server is live and up running on the cloud.

![output 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jgzc4j217e3y8bbsgrdk.PNG)
![output 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3tf3823wmmpn4iu2pnn.PNG)

Thanks for reading this article.

Thanks Gowri M Bhatt for reviewing the content.

If you enjoyed this article, please click on the heart button ♥ and share to help others find it!

The article is also available on [Medium](https://codemaker2016.medium.com/deploy-your-flask-app-on-heroku-36ee31602fe6).

The full source code for this tutorial can be found here,

[GitHub - codemaker2015/heroku-flask-app: flask app configured for hosting on the heroku cloud](https://github.com/codemaker2015/heroku-flask-app)

Useful links,

- [Heroku Documentation | devcenter.heroku.com](https://devcenter.heroku.com/categories/reference)

- [Welcome to Flask - Flask Documentation (2.2.x) | flask.palletsprojects.com](https://flask.palletsprojects.com/en/2.2.x/)