Build Web APIs easily with Python

Vitor Pedro
Analytics Vidhya
Published in
3 min readDec 7, 2019

--

Photo by Chris Ried on Unsplash

Recently I have been working on Web APIs (REST) for different machine learning and computer vision tasks. By using this kind of APIs we can quickly deploy new algorithms, locally or in a Cloud environment, that can be integrated in a broad range of applications (web sites, mobile apps, native apps, etc). With a simple API call we can perform machine learning tasks, such as detecting people or traffic lights in images, in an efficient and scalable way.

In Python, we can easily create a full documented REST API by using two great frameworks: Flask and RESTPlus. Flask is a lightweight web application framework designed for quick development of web applications and allows to scale up to more complex solutions. It is possible to create and start a simple Flask Web Application with just a few lines of code:

from flask import Flaskapp = Flask(__name__)@app.route("/")
def hello():
return "Hello World!"
$ env FLASK_APP=hello.py flask run
* Serving Flask app "hello"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

RESTPlus in an extension for Flask that adds support for developing REST APIs. It provides input validation, automatically generates documentation (with Swagger UI), among other useful features.

The first building block we should know about RESTPlus is resources. With resources we can define functions in Python that will be called when an HTTP request is made (like a GET, POST or PUT request for instance). A basic resource for a note taking application can be coded like this:

from flask import Flask, request
from flask_restplus import Resource, Api

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

notes = {}

@api.route('/<string:note_id>')
class BasicNotes(Resource):
def get(self, note_id):
return {note_id: notes[note_id]}

def put(self, note_id):
notes[note_id] = request.json['content']
return {note_id: notes[note_id]}

if __name__ == '__main__':
app.run()

The @api.route() defines the URL to be used for this resource.

Another great feature of RESTPlus is its built in support for request data validation by using reqparse. Here is a code snippet that can be used inside a resource function:

from flask_restplus import reqparse

parser = reqparse.RequestParser()
parser.add_argument('email', required=True)
parser.add_argument('password', required=True)
data = parser.parse_args()

Using this parser also gives more readable error messages. When an argument fails the validation, RESTPlus will responde with a 400 Bad Request with a message describing the error.

We can also use the fields module to define models for describing the structure of an object of a request or response. Bellow is the note taking application example using this module:

from flask import Flask, request
from flask_restplus import Resource, Api, fields

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

model = api.model('Model', {'content': fields.String})

notes = {}

@api.route('/<string:note_id>')
class BasicNotes(Resource):
def get(self, note_id):
return {note_id: notes[note_id]}

@api.expect(model)
def put(self, note_id):
notes[note_id] = request.json['content']
return {note_id: notes[note_id]}


if __name__ == '__main__':
app.run(debug=True)

The best part is that it automatically documents the APIs and they are visible in the Swagger UI (by accessing http://127.0.0.1:5000/ in this case):

Originally published at https://vitorpedro.com on December 7, 2019.

--

--

Vitor Pedro
Analytics Vidhya

I am a software engineer that has been messing around with computers since I was 6. I have also a great interest in long term investing and personal finance.