Write your first REST API using Python Flask

Since years programming concepts have been evolving with new ideas and improvements. Idea of API, Application Programming Interface, came out to build integration between applications/software/platforms. It has simplified integration between totally different applications and platforms. In early days (even now), APIs were in form of client APIs. Software developers/organizations offer client software component which is many times referred as client library or class. This library is essentially collection of interface and functions to do integration of software with new projects and other software.

Main drawback of this approach is dependency on client library/API. If there is an update/upgrade in application then the client library/API has to be updated across all platforms where ever it is used for integration. To overcome this, idea of more generic form of API forked out. This resulted in inception of SOAP and REST APIs.

Both, SOAP and REST, are based on web protocol and web verbs (GET, POST, PUT, DELETE), where API functions are exposed via HTTP/HTTPS URLs. We wont discuss much of SOAP ( Simple Object Access Protocol) here and directly jump to REST APIs.

REST, REpresentational State Transfer, is a framework which exposes resources and functions of an application over web interface which can be consumed by other applications to do integration. “Resource” can be a database, json data, CSV or anything. “Function” is an operation.

Flask module in python offers really simple and straight forward implementation of RESTful API. You first need to install flask and flask_restful modules.


sudo pip3 install flask flask_restful

Collecting flask
  Downloading https://files.pythonhosted.org/packages/9b/93/628509b8d5dc749656a9641f4caf13540e2cdec85276964ff8f43bbb1d3b/Flask-1.1.1-py2.py3-none-any.whl (94kB)
    100% |████████████████████████████████| 102kB 624kB/s 
Collecting flask_restful
  Downloading https://files.pythonhosted.org/packages/17/44/6e490150ee443ca81d5f88b61bb4bbb133d44d75b0b716ebe92489508da4/Flask_RESTful-0.3.7-py2.py3-none-any.whl

Installing collected packages: flask, flask-restful
Successfully installed flask-1.1.1 flask-restful-0.3.7

Using flask and flask_restful, let us write a simple Web Service (REST API) which will perform retrieval, add, update and delete operations on following json data set of City, Country pairs.


CityCountry = { "Delhi" : "India", "Bombay" : "India", "Tokyo" : "Japan", "Paris" : "France" }

Here is the code:


#!/usr/bin/python3
# myrest.py

from flask import Flask, request, jsonify
from flask_restful import Resource, Api
import json

app = Flask(__name__)
api = Api(app)

CityCountry = { "Delhi" : "India", "Bombay" : "India", "Tokyo" : "Japan", "Paris" : "France" }

class gettask(Resource):
    def get(self, City):
        if City == "All" :
           Cities = CityCountry.keys()
           Countries = CityCountry.values()
           return CityCountry, 200
        else:
           return CityCountry.get(City), 200

class pubtask(Resource):
    def post(self):
        new_item = request.get_json(force=True)
        CityCountry.update(new_item)
        return CityCountry, 201

class uptask(Resource):
    def put(self):
        new_item = request.get_json(force=True)
        CityCountry.update(new_item)
        return CityCountry, 202

class deltask(Resource):
    def delete(self, City):
        del CityCountry[City]
        return CityCountry, 203

api.add_resource(gettask, '/pulldata/<string:City>')
api.add_resource(pubtask, '/pushdata/')
api.add_resource(uptask, '/updata/')
api.add_resource(deltask, '/deldata/<string:City>')

if __name__ == '__main__':
     app.run(host='0.0.0.0', port='8000', debug=True)

Lets fire the code:


./myrest.py 
 * Serving Flask app "myrest" (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://0.0.0.0:8000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 225-205-506

Now try to fetch All data and then country of City Tokyo (GET verb)


curl "http://192.168.0.17:8000/pulldata/All"
{
    "Delhi": "India",
    "Bombay": "India",
    "Tokyo": "Japan",
    "Paris": "France"
}

curl "http://192.168.0.17:8000/pulldata/Tokyo"
"Japan"

Let us add two pairs of City, Country to dataset (POST verb)


curl -d "{ \"Sydney\" : \"Australia\", \"Berlin\" : \"Germany\"}" -X POST "http://192.168.0.17:8000/pushdata/"
{
    "Delhi": "India",
    "Bombay": "India",
    "Tokyo": "Japan",
    "Paris": "France",
    "Sydney": "Australia",
    "Berlin": "Germany"
}

Update “Bombay” city mapping from “India” to “Maharashtra” (PUT verb)


curl -d "{ \"Bombay\" : \"Maharashtra\"}" -X PUT "http://192.168.0.17:8000/updata/"
{
    "Delhi": "Goa",
    "Bombay": "Maharashtra",
    "Tokyo": "Japan",
    "Paris": "France",
    "Sydney": "Australia",
    "Berlin": "Germany"
}

Last operation, try to delete record where City is “Berlin” (DELETE verb)


curl -X DELETE "http://192.168.0.17:8000/deldata/Berlin"
{
    "Delhi": "Goa",
    "Bombay": "Maharashtra",
    "Tokyo": "Japan",
    "Paris": "France",
    "Sydney": "Australia"
}