sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
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.
-
Part 1. Introduction to Flask and creating REST API
Prerequisite
-
MacBook or an Ubuntu Machine with root privileges
-
Python 3.6+
-
Any IDE like PyCharm or IntelliJ IDEA
-
Docker
-
Jenkins
What will you learn?
-
Setting up environment
-
Installing Python 3.6 on Mac/Ubuntu
-
What is PIP
-
Why use virtual environment, setup virtual environment
-
-
Introduction to flask
-
What is Flask?
-
Installing Flask
-
-
Creating a Flask app
-
What is REST API why to use it
-
Creating a REST api in Flask
-
Running the Flask app
-
Testing REST endpoint using curl
-
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
PIP
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:
-
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.
-
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
$ pip install virtualenv
$ 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
$ 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:
$ 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:
$ pip install flask
$ pip freeze -l > requirements.txt
$ 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:
-
Werkzeug, a WSGI utility library
-
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.
-
GET
-
To retrieve a resource, you shall use HTTP GET. We should not modify the state of resources using HTTP GET method ever.
-
-
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.
-
-
PUT
-
To change the state of a resource or to update it on the server, use PUT
-
-
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:
-
GET / will return hello world
-
GET /health.json will return a json with hardcoded status for the app
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:
-
Open terminal
-
Go to project folder
-
Activate virtual environment
-
Run the main file
cd project_directory
source venv/bin/activate
python src/main.py
* 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
If you have curl installed on your system, you can use below command to test the behavior of Flask REST endpoint.
$ curl -v -X GET http://localhost:5000/health.json
* 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
Click here for the next article in this series.
Top articles in this category:
- Flask Interview Questions
- Part 3: Dockerize Flask application and build CI/CD pipeline in Jenkins
- Part 2: Deploy Flask API in production using WSGI gunicorn with nginx reverse proxy
- Named Entity Recognition using spaCy and Flask
- Deploying Keras Model in Production using Flask
- Blueprints in Flask API Development
- Top 100 interview questions on Data Science & Machine Learning