Part 1: Creating and testing Flask REST API

Upasana | August 31, 2019 | 7 min read | 1,838 views | Flask - Python micro web framework


This concise tutorial will walk you through Flask REST API from development to production.
All articles in this Series

Prerequisite

  1. MacBook or an Ubuntu Machine with root privileges

  2. Python 3.6+

  3. Any IDE like PyCharm or IntelliJ IDEA

  4. Docker

  5. Jenkins

What will you learn?

  1. Setting up environment

    1. Installing Python 3.6 on Mac/Ubuntu

    2. What is PIP

    3. Why use virtual environment, setup virtual environment

  2. Introduction to flask

    1. What is Flask?

    2. Installing Flask

  3. Creating a Flask app

    1. What is REST API why to use it

    2. Creating a REST api in Flask

    3. Running the Flask app

    4. Testing REST endpoint using curl

    5. Testing REST endpoint using POSTMAN

Setup environment

Getting PyCharm (Community or Pro)

You can download PyCharm IDE for development from Jetbrains website. There are two flavours available: Community Edition (Free) and Pro Edition (Paid).

Here is the feature comparision between Pro and Community edition:

Installing Python 3.6 on Mac

In this tutorial, we will be working using python 3.6. To install python 3.6 on mac, you need to follow this link : https://www.python.org/downloads/mac-osx/

From here you can download python installer as per mac’s configuration. Be sure to download python3.6 installer which will be in .dmg format.

Open the .dmg file and click on continue to install python3.6

Installing Python 3.6 on Ubuntu

For installing python 3.6 on ubuntu, just follow the following commands

sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6

PIP

What is PIP

PIP is a package manager for Python packages, or modules if you like. Python 3.4 onward ships with PIP included by default, so you don’t need to install it separately.

Install a package using pip
$ pip install camelcase
Uninstall package using pip
$ pip uninstall camelcase
List packages
$ pip list

Why use Virtual Environment?

We normally have to use different versions of pythons in different projects as per need basis (web projects, batch jobs, command line tools, machine learning programs). Even the dependencies and package versions may be different for each of project.

Virtual environment help us in creating a completely isolated environment for the given project. That means each of project can have its own python version, dependencies and package version rather than one universal version for all projects. This approach has many benefits:

  1. Its very easy to move a project through different stages of its lifecycle - dev to qa to stage and finally production. Virtual environment will keep its own version of packages for the given project.

  2. Completely isolated environment reduces chances of environment related issues in project. So testing becomes easy and scope for bugs is reduced.

Setup virtual environment

Run the below command on the terminal to install virtual environment on your machine

Install virtualenv using pip
$ pip install virtualenv
Create virtual environment
$ virtualenv -p python3.6 venv

where venv is the name of the virtual environment. Above command will create a virtual environment in the current directory with name venv

To activate this newly create virtual environment, you need to run the below command

Activate virutal environment
$ source venv/bin/activate

Now if you already have a requirements file, you can install all the project specific dependencies in this virtual environment using below command:

Install requirements
$ pip install -r requirements.txt

If you want to install additional dependencies that are not present in requirements.txt, you can run the below command:

Installing flask using pip
$ pip install flask
Freeze all local packages
$ pip freeze -l > requirements.txt
Deactivate virtual environment
$ deactivate

Any python command will now use the system’s default python environment after we deactivate the virtual environment.

Introduction to Flask

What is Flask?

Flask is a micro web framework written in python, which is frequently used by developers to create REST endpoints.

It is part of the categories of the micro-framework which are normally known as a framework with little to no dependencies to external libraries. This has pros and cons both. Pros would be that the framework is light, there are little dependency to update and watch for security bugs, cons is that some time you will have to do more work by yourself or increase yourself the list of dependencies by adding plugins. In the case of Flask, its dependencies are:

  1. Werkzeug, a WSGI utility library

  2. jinja2, which is its template engine

Installing Flask

We will be installing flask module using pip

$ pip install flask

Creating a Flask App

What is REST API why to use it

A RESTful API is an API (application program interface ) that uses HTTP requests to GET, PUT, POST and DELETE data.

  1. GET

    • To retrieve a resource, you shall use HTTP GET. We should not modify the state of resources using HTTP GET method ever.

  2. POST

    • To create a resource on the server, use HTTP POST. An example could be new user registration REST endpoint, it will create a new user in the system.

  3. PUT

    • To change the state of a resource or to update it on the server, use PUT

  4. DELETE

    • To remove or delete a resource on server, use DELETE

Creating a REST api in Flask

In this section, we will create a hello world flask application that will have two endpoints:

  1. GET / will return hello world

  2. GET /health.json will return a json with hardcoded status for the app

src/main.py
from flask import Flask, jsonify    (1)

app = Flask(__name__)   (2)


@app.route("/")
def home():
    return "Hello, World!"


@app.route("/health.json")  (3)
def health():
    return jsonify({"status": "UP"}), 200   (4)


if __name__ == "__main__":
    app.run(debug=True)
1 we are importing Flask and jsonify from flask module
2 We use name in Flask when we are using single module, otherwise we can give a name as well to flask app when using blueprints
3 declaring a http route with mapping /health.json relative to web server root
4 Using jsonify to return json response from the given key value pair with HTTP 200 response code

Run flask app

To run the flask app, we will be following these steps:

  1. Open terminal

  2. Go to project folder

  3. Activate virtual environment

  4. Run the main file

cd project_directory
source venv/bin/activate
python src/main.py
Output
 * Serving Flask app "main" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 874-012-700

Since, we haven’t give any specific host and port to flask app, so it will run on default host and port which are 127.0.0.1 and 5000 respectively.

If you want to change host & port then you can add these arguments in app.run like:

app.run(host='12.23.34.45',port=7777,debug=True)

Testing REST endpoint using curl

What is curl

curl is a command line tool for doing all sorts of URL manipulations and transfers, using one of the supported protocol (FTP, HTTP, HTTPS, etc.)

Install curl on macOSX
$ brew install curl
Install curl on Linux
$ sudo apt-get install curl

You should have homebrew installed on your mac to run this command successfully.

If you have curl installed on your system, you can use below command to test the behavior of Flask REST endpoint.

Request
$ curl -v -X GET http://localhost:5000/health.json
Response Body
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 21
< Server: Werkzeug/0.15.1 Python/3.6.7
< Date: Mon, 01 Apr 2019 17:52:05 GMT
<
{
  "status": "UP"
}

As we can see, server is returning a application/json mimetype of response with the health status json.

Testing REST endpoint using POSTMAN

Postman is the only complete API development environment, and flexibly integrates with the software development cycle. We can test REST APIs through POSTMAN easily.

Now we will accessing endpoint via POSTMAN.

We can use any of localhost or 127.0.0.1 for accessing endpoint. You can see the images below for referring on how it will look like on postman

getendpoint
localhost
127health

Click here for the next article in this series.


Top articles in this category:
  1. Flask Interview Questions
  2. Part 3: Dockerize Flask application and build CI/CD pipeline in Jenkins
  3. Part 2: Deploy Flask API in production using WSGI gunicorn with nginx reverse proxy
  4. Named Entity Recognition using spaCy and Flask
  5. Deploying Keras Model in Production using Flask
  6. Blueprints in Flask API Development
  7. Top 100 interview questions on Data Science & Machine Learning

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.