Building RESTful APIs using Flask

Learn about using the lightweight web framework in Python from this article.



By Mahadev Easwar, Data Engineer



Flask Framework

 

What is an API?


An Application Programming Interface (API) is a software intermediary that allows two applications to communicate.


What is a web framework and why is it useful?

A web framework is a software framework that is created to support the development of dynamic sites, web services, and web applications. A web framework is a code library that makes web development quicker and easier by giving basic patterns for building reliable, scalable, and maintainable web applications ¹.

Flask: Introduction

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.



No. of Package Downloads Last Month. Source. ²

 

Why is it a microframework?


“Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible ³.


Flask offers suggestions but doesn’t enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that makes adding new functionality easy ⁴.

Why use Flask?

  • Easy to set up
  • Minimalistic
  • Flexible to add any extensions for more functionalities
  • Active community

In this article, I will demonstrate how to set up, build and run a simple Flask application.

Package Installation

It is generally recommended to install packages in a virtual environment specific to the project.

# command prompt
pip install Flask




Installing Flask package

 

JSON

JSON is a generic data format with a minimal number of value types: strings, numbers, booleans, lists, objects, and null. Although the notation is a subset of JavaScript, these types are represented in all common programming languages, making JSON a good candidate to transmit data across language gaps ⁵.

# JSON Example:
{
"id" : 1,
"name" : "john"
"age" : "25",
"activities" : ["cricket","football"],
"class" : [{"year":"2020","dept":"CSE"}]
}


Building a Flask App

I will build a simple application using Flask that will access employee data and return the info requested in the input. We will send and receive the data both using JSON file format. Since I will be giving a data-based demonstration, I’m loading the pandas package too.

1. Importing the required packages

from flask import Flask, request, jsonify 
import pandas as pd


The directory structure of the project would be as follows

Demo/
| — emp_info.csv
| — emp_status.csv
| — app.py


2. Creating an application instance

app = Flask(__name__)


3. Declaring the endpoint using .route() and accepted methods like POSTGET. By default, it just listens for GET method. Let us enable just the POST method for this API.

@app.route("/get_emp_info", methods = ['POST'])


4. Defining the functionality that the application will perform. Retrieving the employee data from CSV files based on the input data.

@app.route("/get_emp_info", methods = ['POST'])
def get_employee_record():
    input_data = json.loads(request.get_json())
    ids = input_data['emp_ids']
    status = input_data['status']
    emp_info = pd.read_csv('emp_info.csv')
    emp_status = pd.read_csv('emp_status.csv')
    emp_status = emp_status[(emp_status['emp_no'].isin(ids)) &     (emp_status['status'].isin(status))]
    emp_info = emp_info[emp_info['emp_no'].isin(emp_status['emp_no'])]
    emp_info = pd.merge(emp_info,emp_status,on='emp_no',how='left')
    out_data = emp_info.to_dict(orient='records')
    return jsonify(out_data)


The jsonify() is a helper method provided by Flask to properly return JSON data. It returns a Response object with the application/json mimetype set.

5. Setting the Python application to run on the local development server. By default, the debug mode is False. To restart the service as and when code is modified, the debug mode can be set to True.

# Setting port number and host i.e., localhost by default
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=6123)




Python Flask Application

 

6. Running the Python program on the local server

# command prompt
python app.py




Running the Python Application

 

Testing the Application

Using the requests package to send a POST request to the developed application.

# command prompt - installing requests package
$ pip install requests# Python code to test
import requests, json
# sample request
data = {"emp_ids":["1001","1002","1003"],"status":["active"]}
# Hitting the API with a POST request
ot = requests.post(url='http://localhost:6123/get_emp_info', json=json.dumps(data))
print(ot.json())# Response JSON 
[{
 'cmp': 'ABC',
 'emp_no': 1001,
 'name': 'Ben',
 'salary': 100000,
 'status': 'active'
}, {
 'cmp': 'MNC',
 'emp_no': 1002,
 'name': 'Jon',
 'salary': 200000,
 'status': 'active'
}]


Summary

Concepts we’ve covered in this article:

  • API & Web framework
  • Flask Introduction
  • Setting up Flask environment
  • Building a Flask API
  • Testing the Flask API with a request using the requests package

Flask is like the minimalist approach to building RESTful APIs.


It is always the simple that produces the marvelous. — Amelia Barr


Wrapping Up

Thanks to anyone who has made it this far. I hope you found this article helpful. Please share your feedback/queries in the comments. Now, it’s time for you to build your own APIs from scratch. Wish you luck!

If you found this article interesting and are passionate about Data Science, Data Engineering, or Software Engineering hit follow and feel free to add me on LinkedIn.

 
Bio: Mahadev Easwar is a Data Engineer with notable skills in Python, R, and SQL.

Original. Reposted with permission.

Related: