Flask

Flask Rest API example with Python

Google+ Pinterest LinkedIn Tumblr

In this article we will show you how to build simple restful API with Flask which has capabilities to Create, Read, Update and delete from Notes.

We are going to use Flask-API in this tutorial which is drop-in replacement for Flask that provides an implementation of browsable APIs similar to DJango REST Framework provides, It gives you property content with response and smart request parsing.

First of all we need to create virtual Environment for Python and install required libraries

# create virtaul environment
python3 -m venv env

# activate virtual envionment
source env/bin/activate

# install flask 
pip install flask

# install Flask-API
pip install Flask-API

once required installation is completed, we can start programming part for API , let’s import and initialize your application :

from flask_api import FlaskAPI

app = FlaskAPI(__name__)

The following example demonstrate a simple API for creating , listing , updating and deleting notes. Save mentioned file as app.py

# imports
from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions

# app intialize
app = FlaskAPI(__name__)

# notes dummy data
notes = {
    0: 'This is Note1',
    1: 'This is Note2',
    2: 'This is Note2',
}

# notes representation
def note_repr(key):
    return {
        'url': request.host_url.rstrip('/') + url_for('notes_details', key=key),
        'text': notes[key]
    }

# notes list and insert functions
@app.route("/", methods=['GET', 'POST'])
def notes_list():
    if request.method == 'POST':
        note = str(request.data.get('text', ''))
        idx = max(notes.keys())+1
        notes[idx] = note
        return note_repr(idx), status.HTTP_201_CREATED

    return [note_repr(idx) for idx in sorted(notes.keys())]


# notes details function update, delete
@app.route("/<int:key>/", methods=['GET', 'PUT', 'DELETE'])
def notes_details(key):

    if request.method == 'PUT':
        note = str(request.data.get('text', ''))
        notes[key] = note
        return note_repr(key)

    elif request.method == 'DELETE':
        notes.pop(key, None)
        return '', status.HTTP_204_NO_CONTENT

    if key not in notes:
        raise exceptions.NotFound()
    return note_repr(key)


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

Now, Run the webapp with below command

python app.py

Output :

You can open API directly in browser by opening http://127.0.0.1:5000/ and you can navigate between notes and make GET, PUT , POST , DELETE API requests.

Write A Comment