Python REST service using Flask

Wanting to create a Python based REST service? Let’s use Flask and see what we can do.

Start off by installing Flask

pip install Flask

Now let’s write some code

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

app.run()

This is nice and simple and pretty obvious how things work. As you can see we create the Flash application and in this sample run it (although on the Flask website they often show running the Flask Run from the Python command line).

Each “route” is defined and mapped directly to a function. In this example the root of the URL is mapped to the hello function.

The route can also contain variables which are show within <>, for example

@app.route('/<name>')
def hello(name):
    return f"Hello {name}"

We can also define converters (similar to declaring the type of the variable) for the variables, so for example if we need to access something by an integer id, the we might have

@app.route('/employee/<int:id>')
def employee(id):
    return f"Employee {id}"

By default the converter used (as you’d probably expect) is string, but Flask also supports int, float, path, any and uuid.

By default each route is using the HTTP method GET, but we can also define the supported methods for each route, i.e.

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()

References

Flask is Fun