Getting Started With Flask-RESTful API And Deploying to Heroku
By: Samir Khanal
Tags: Flask, Flask Restful, Python, Python Flask, Heroku

Introduction

Let’s get started with some basic topics that we should know before diving into the coding and deploying section.

What is Flask?

Flask is a simple and powerful micro web framework. It is mostly used for creating APIs in Python. Flask depends on the Jinja template engine and the Werkzeug WSGI toolkit. The “micro” in micro web framework means Flask aims to keep the core simple but extensible.

Flask does not include a database abstraction layer, form validation or anything else where different libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your application as if it was implemented in Flask itself. Numerous extensions provide database integration, form validation, upload handling, various open authentication technologies, and more. Flask may be “micro”, but it’s ready for production use on a variety of needs. You can check the official Flask documentation here.

What is an API?

API stand for Application Programming Interface. It provides a software interface or acts as an intermediary which allows two applications to talk to each other. For Example: When we login to Facebook, the Facebook-app calls an User Authentication API which verifies our Facebook account is valid or not and gives us access to our respective user accounts. For Flask-API, We can get started from its official documentation given here.

What is an Flask-RESTful? Flask-RESTful is an extension to Flask for building REST APIs. You can check its official documentation here.

Source: FlaskRESTful official documentation

What is an REST API?

REST stands for “Representational State Transfer”. It is a set of rules(or design pattern) that developers follow when they create their API.

A RESTful API uses commands to obtain resources.These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. The state of a resource at any given timestamp is called a resource representation and the API calls are stateless.

A RESTful API uses existing HTTP methodologies for operations , such as:

GET to retrieve a resource;

PUT to change the state of or update a resource, which can be an object, file or block;

POST to create that resource; and

DELETE to remove it.

Example

Now, After the basic introduction, Let’s get started with the coding section.

Lets create a directory named flask-restful-heroku . Then, in this directory, create a virtual environment named venv.

$ virtualenv venv

Activate the created virtual environment.

$ source ./venv/bin/activate

Now, Install Flask and Flask-RESTful.

$ pip install Flask

$ pip install flask-restful

We will use gunicorn for server.

$ pip install gunicorn

Create a file named main.py in the project directory. The directory will look like this:

Copy the code below to main.py . It is a minimal Flask-RESTful API.

Save the file main.py and run it using your python interpreter.

$ python main.py

It will look as below.

To run the file using WSGI server, first stop the flask app by pressing CTRL+C.

Then, create a file named wsgi.py on the project directory. The directory will look like this:

Now, copy the code below to wsgi.py . We are making the file ready to run with WSGI server.

Then, run the file using WSGI server.

$ flask run

Then, follow the URL by CTRL+Click on url. You will be redirected to a new tab on your default browser to the url. You will get following output in your browser.

Here, it will be easy for us if the flask is running on debug mode. so, the changes are automatically implemented.So, stop the production server with CTRL+C and again run the file main.py using python interpreter. Follow the URL by CTRL+Click on url. You will be redirected to a new tab on your default browser to the url. You will get the same output as above.

from flask import Flask, jsonify

from flask_restful import Resource, Api

Here, we have imported the required libraries Flask, jsonify, Resource and Api. ‘jsonify’ is used to convert Python dict structures to json format.

app = Flask(__name__)

api = Api(app)

First, We have initialized and flask app. Then, we have assigned the flask app as an api.

class HelloWorld(Resource):

def get(self):

return {'hello': 'world'}

HelloWorld is a class which acts as an api resource. The function get acts as get request. If we have to deal with post request, we can create a function named post and do post request inside that function. As HelloWorld is an api resource, its function acts as different types of api requests.

api.add_resource(HelloWorld, '/')

This line adds HelloWorld as an resource with url ‘/’ for the api.

if __name__ == '__main__':

app.run(debug=True)

Every Python module has it’s __name__ defined and if this is ‘__main__’, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions. And it also means that if the current file-name is equals to the main file-name then run the app.

The syntax debug=True runs the file in debugging mode where the change on code is automatically changed to the server.

Lets modify main.py . First delete HelloWorld class and create a class with class-name status which returns response of status of api as:

class status(Resource):

def get(self):

try:

return {'data': 'Api running'}

except(error):

return {'data': error}

It simply provides the status information of the api.

Then create another class with class-name Sum, which returns the sum of provided two numbers through get request as:

class Sum(Resource):

def get(self, a, b):

return jsonify({'data': a+b})

Now, lets add them as resource with assigned urls.

api.add_resource(status,'/') api.add_resource(Sum,'/add/<int:a>,<int:b>')

We will remove debug=true in main.py as we are now going for the production and deployment in Heroku.

There is a concept of Cross-Origin in case of APIs’ . It means that even if we have developed our API with python, Other origins(languages like Javascript, React) can also access our API. So, we will also import CORS and assign our app as an CORS app.

Install the flask-cors as:

$ pip install Flask-Cors

Finally, our main.py will look like the following:

We have our wsgi.py as it is.

Deplyoing to Heroku

Before deplyoing to Heroku, We have to have some additional files.

Add a file named Procfile with inner contents:

web: gunicorn main:app

It means the app is an web application which runs on gunicorn server and main is our app.

Create another file named runtime.txt with inner contents:

python-3.7.3

Which is the python version I am currently using.

Now, on the terminal type:

pip freeze > requirements.txt

It will create a requirements.txt file with the needed requirements for this app. Open the requirements.txt file and you can see the requirements specified as shown in the following figure.

Our final file directory will look like this:

Install the Heroku CLI and follow the commands stepwise.

$ heroku login

Follow the procedures and login .

Now, lets create a new heroku app named flask-heroku1. Give your unique app name.

heroku create flask-heroku1 --buildpack heroku/python

You can check your heroku dashboard whether above code worked or not.

Here, we have specified buildpack as python because our app is in Python. And during deployment heroku builds our app according to Python buildpack.

$ git init

If you don’t have git installed then first install git and continue.

$ git add .

This command stands all changed files as changes. Now, we commit to our local git repository we have just initialized.

$ git commit -m "Flask-Restful-Heroku api"

Sometimes, our heroku create-app doesnot set remote origin. So, we have to add remote origin as:

$ heroku git:remote -a flask-heroku1p

Finally, deploy to heroku as:

$ git push heroku master

Then you can see the deployment process as:

Requirements on requirements.txt are being installed using pip

The deployment is completed . My api is hosted at:

https://flask-heroku1p.herokuapp.com/

It gives:

get request output of root url of api

I will get the sum of two numbers by entering the following url:

https://flask-heroku1p.herokuapp.com/add/3,5

It gives:

get request output of sum of 3 and 5

References: