A simple REST service with Python Flask

This is a simple REST service written in Python with Flask for running some tests. It is based on the excellent tutorial from Miguel Grinberg (accessible here). The service simply returns a hard coded JSON string.

The goal of this simple script is to have a simple, local sandbox for testing querying HTTP services. This script will be modified as I will be in need to test more and more functionalities and libraries. Flask is a very powerful library for creating web services and applications very fast. It has a very steep learning curve and takes advantage of all Python’s libraries out there.

Flask logo

The code:

from flask import Flask
from flask import render_template
import json

app = Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
    posts = [
        {
            'author': {'username': 'John'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author': {'username': 'Susan'},
            'body': 'The Avengers movie was so cool!'
        }
    ]

    return json.dumps(posts)

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

The script, once executed, will create an HTTP service, listening on 127.0.0.1:5000 (this can be changed in app.run(), for example with app.run(host=’0.0.0.0′, port=80) the service will listen in all the interfaces on the port 80). The script will also return the following JSON code:

[
    {
        'author': {'username': 'John'},
        'body': 'Beautiful day in Portland!'
    },
    {
        'author': {'username': 'Susan'},
        'body': 'The Avengers movie was so cool!'
    }
]