Create an API in Python real quick with Flask

Flask is a micro web framework written in Python.

Being a microframework, it does not require particular tools or libraries.

You can install it using pip.

In my system I have pip pointing to Python 2 and pip3 pointing to Python 3, and since I’m going to use Python 3, I will install it with pip3.

pip3 install flask

If Python 3 is your default Python, just do:

pip install flask

To code a quick API with Flask, the code below is all you need.

First import Flask and instantiate an app object giving it a name.

Then define a route for the first endpoint, in this case it goes to the root, no extra context.

The first @app part matches the name of the object app instantiated, than use route('/') indicating the route.

Right below it you can write a function that will be called when you access the route defined.

In this case, the function returns a simple phrase "My first API.".

Finally you run your app using app.run().

from flask import Flask

app = Flask('my_app')

@app.route('/')
def home():
    return "My first API."

app.run()

Save the code above in a file named main.py.

To run it just execute the code in a terminal:

python3 main.py

If Python 3 is your default Python, just do:

python main.py

You should see an output similar to this saying a development server is running on http://127.0.0.1:5000/.

 * Serving Flask app "my_app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [15/May/2020 08:47:47] "GET / HTTP/1.1" 200 -

If you open http://127.0.0.1:5000/ in your browser you should see the phrase ‘My first API.’.

Notice that the names given are arbitrary and to call the instance of Flask as app is a mere convention.

I could change everything to banana and it would still work.

from flask import Flask

banana = Flask('banana')

@banana.route('/')
def home():
    return "My first API."

banana.run()

I also recommend reading this post to see how to create an API using a different framework: Django REST Framework: API in a few minutes in Python.