Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: [email protected]
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

Take our 85+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

Publication

Building RESTful APIs using Flask
Latest

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

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 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
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.

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

Feedback ↓