Creating REST Services With Flask

DZone 's Guide to

Creating REST Services With Flask

The prerequisites for this tutorial is a basic knowledge of Python, Virtual Environments, and a basic understanding of REST architecture.

· Integration Zone ·
Free Resource

Previously, I wrote about creating web services with Node.js frameworks Express and Hapi, and now, you will see how it is easy to create a REST API in Python using the Flask framework.

As you all know, Python is popular in the machine learning world, but as a general programming language, it can also be used to create web APIs. So you can create your machine learning model in Python and can serve it as a RESTful web service with Flask. In this article, we will not be talking about machine learning model creation, maybe in another article in the future.

The prerequisites for this tutorial is a basic knowledge of Python, Virtual Environments, and a basic understanding of REST architecture. 

We begin by creating a virtual environment.

>mkproject restinflask
Using base prefix 'd:\\dev\\platforms\\python\\python36'
New python executable in D:\dev\platforms\Python\workon\restinflask\Scripts\python.exe
Installing setuptools, pip, wheel...done.

    "D:\dev\workspaces\python\restinflask" is now the project directory for
    virtualenv "D:\dev\platforms\Python\workon\restinflask"

    "D:\dev\workspaces\python\restinflask" added to

(restinflask) >

Now we need to install flask and flask-RESTful packages:

(restinflask) D:\dev\workspaces\python\restinflask>pip install flask flask-RESTful
Collecting flask
Collecting flask-RESTful
Successfully installed Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 aniso8601-3.0.2 click-6.7 flask-1.0.2 flask-RESTful-0.3.6 itsdangerous-0.24 pytz-2018.4 six-1.11.0
(restinflask) D:\dev\workspaces\python\restinflask>

Now it is time to create our entry application file app.py:

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

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

items = []

first, you need to create a new class, 

class ItemList(Resource):
    def get(self):
        return {'items':items}, 200

class Item(Resource):
    def _find_item(self, name):
        return next(filter(lambda i: i["name"] == name, items), None)

    def get(self, name):
        item = self._find_item(name)
        return {"item": item}, 200 if item is not None else 404

    def post(self, name):
        existing_item = self._find_item(name)
        if existing_item is not None:
            return {"message": "Item already created"}, 409
        data = request.get_json()
        new_item = {"name": name, "price":data["price"]}

        return {"item": new_item}, 201

    def put(self, name):
        data = request.get_json()
        existing_item = self._find_item(name)
        if existing_item is not None:
            return {"item": existing_item}, 201
            new_item = {"name": name, "price": data["price"]}
            return {"item": new_item}, 201

api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')


The lines 4, 5, 33, and 35 are the boilerplate codes, which bootstraps the application.
Lines from 9 through 31 implements the API. Our Item class implements the Resource class which maps HTTP verbs to methods. The get post , and put  methods are to handle corresponding Http methods.

Now let's run the application and test it:

(restinflask) D:\dev\workspaces\python\restinflask>pyhton app.py
 * Serving Flask app "api" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on (Press CTRL+C to quit)

First, create a table item with price 13.57.

Image title

Now query it with an http-get;

Image title

Update the existing item with an http-put;

Image title

You can find the whole project in my GitHub repository

rest api ,python ,flask ,tutorial ,integration

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}