Over a million developers have joined DZone.

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

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

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 = []

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>')


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

With SnapLogic’s integration platform you can save millions of dollars, increase integrator productivity by 5X, and reduce integration time to value by 90%. Sign up for our risk-free 30-day trial!

rest api ,python ,flask ,tutorial ,integration

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}