Building RESTful APIs using Flask
Last Updated on January 6, 2023 by Editorial Team
Last Updated on May 13, 2021 by Editorial Team
Author(s): Mahadev Easwar
Programming
Lightweight Web Framework inΒ Python
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.
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
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.
- 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 POST, GET. 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)
6. Running the Python program on the localΒ server
# command prompt
python app.py
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.
REFERENCES:
1. https://www.goodfirms.co/glossary/web-framework/
2. https://pypistats.org/
3. https://flask.palletsprojects.com/
4. https://github.com/pallets/flask
5. https://www.infoworld.com/article/3222851/what-is-json-a-better-format-for-data-exchange.html
Building RESTful APIs using Flask was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.
Published via Towards AI