Build an API with Python Flask

Build an API with Python Flask

An introduction into Python Flask with added code samples.

Introduction

Flask is a powerful Python library used for creating APIs. If you want to get started building your own API with Python, and learning a bit about how APIs work both as an API user and an API builder then this guide will get you started.

In this article, we setup a simple Flask API for sending data. The API can be deployed locally so that you can test it in your browser or in your terminal. We assume that you are operating a machine that has Python installed, and the corresponding Python package manager, Pip.

What is an API?

An API (Application Programming Interface) allows different systems to talk to each other and share data. We expect an API to take the form of a URL that will return some data, typically in JSON format. Similarly, we can send data to APIs, in exchange for a message confirming or denying whether the data has been received by the database.

Example: Getting data

The following URL will return some sample data.

https://api.csvgetter.com/YWaeOXW0OVzEEdbFm3bf?type=json_records

Response

[
    {
        "Name": "John Doe",
        "Age": 35,
        "Gender": "Male",
        "Occupation": "Engineer"
    },
    {
        "Name": "Jane Smith",
        "Age": 28,
        "Gender": "Female",
        "Occupation": "Doctor"
    },
    {
        "Name": "Michael Johnson",
        "Age": 42,
        "Gender": "Male",
        "Occupation": "Teacher"
    },
    {
        "Name": "Emily Brown",
        "Age": 31,
        "Gender": "Female",
        "Occupation": "Software Developer"
    },
    {
        "Name": "David Wilson",
        "Age": 45,
        "Gender": "Male",
        "Occupation": "Manager"
    }
]

You can test this API yourself, and a great tool to download when working with APIs is Postman. Postman formats API responses really nicely and gives you a clear view of how your API works. Or you can try the API in your terminal with the following command.

curl https://api.csvgetter.com/YWaeOXW0OVzEEdbFm3bf?type=json_records

Or just try it in your web browser!

Building an API with Python

How do we write the Python code that produces a simple API? This can be made possible using Flask. If you have not installed Flask already, then you can install Flask with pip.

pip install flask

What is Flask?

Flask will allow us to build an API with API routes. Think of each API route as a Python function. With Flask routes, we will be able to create the online URLs needed to run our Python functions and return data.

When using the Flask library, you can test your API locally and make api requests to localhost:8080. Localhost will essentially behave as the web address of your API whilst it is in development and will equivocate to a real API endpoint like https://api.csvgetter.com.

Starter Script

The following code, if pasted into a python script, is all you need to get started building an API. Paste the following code into a python file with a name like main.py.

from flask import Flask, jsonify

import os

app = Flask(__name__)

@app.route("/", methods=["GET"])
def uptime_check():
    response = {
        "status": "up",
        "message": "Server is running",
    }
    return jsonify(response), 200


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
What does this code do?
  • from flask import Flask imports the flask functions we need to build our API.

  • similarly we import functions from jsonify which is a handy library for structuring data in json format - perfect for returning a response from our API.

  • We will also use the os library so we import this as well.

  • app = Flask(__name__) - initialises a flask app, our API.

  • We then declare an @app.route, which is the important part of our API. '/' indicates the home route, essentially the api response of curl localhost:8080. (If our app route was to be called ‘/hello’, then the code would run when we use curl localhost:8080/hello.) When the route is used, we will run the python function uptime_check(). The function will confirm to the user that the API is alive and well by returning some JSON.

  • Finally, the last few lines of the script start the API.

Here is what you should see when you run your python script

python main.py
 * Serving Flask app 'main'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8080
 * Running on http://172.30.241.108:8080
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 310-770-429

Your API will stop when you either close terminal, use a keyboard command, or find a way to break it by adding some bad code. You can always shut down the python script with Ctrl + C or Cmd + C.

Testing it

We can now test your api by visiting http://localhost:8080 as a web address. You can test this in your browser by visiting the URL just like you would a web URL, or in terminal with the following command. (Make sure you open a new window or tab in terminal, as you will not be able to use this command in the same terminal where your api is running.)

curl localhost:8080

When you test the API, you should notice a JSON response in terminal (or in your browser) of the following format:

{
  "message": "Server is running",
  "status": "up"
}

You should also notice a log appear in the terminal that is running the Python Flask API.

127.0.0.1 - - [date and time] "GET / HTTP/1.1" 200 -

This is a simple log to demonstrate that the API was used, and that the status code given to the user was 200. In API Status code language, a 200 symbolises that all is well, and that the API user received the data they expected. An API will return both response data (the json), and a response status code (the 200). Here are some other API status codes you may recognise:

  • 404: Not found. The API endpoint does not exist. We can get this status code from our local API by trying a route that we have not added to our code. I.E curl localhost:8080/unknown.

  • 401: Unauthorised. If the correct authentication token is not added. Learn more about APIs and authentication here.

  • 400: Bad request. If you pass data to the API in the wrong format

  • 500: Server side error. This will happen if the code needed to run the API breaks, for instance if we wrote some bad Python code in our Flask app.

Expanding our API

We can expand our API a little bit by adding more routes. Below will show you how to make another route which will return some information about our API.

from flask import Flask, jsonify

import os

app = Flask(__name__)

@app.route("/", methods=["GET"])
def uptime_check():
    response = {
        "status": "up",
        "message": "Server is running",
    }
    return jsonify(response), 200

@app.route("/info", methods=["GET"])
def app_info():
    info = {
        "app": "Demo Flask API",
        "version": "1.0",
        "author": "Your Name",
        "description": "This is a simple API built with Flask for demo purposes."
    }
    return jsonify(info), 200

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

Now try the following URL:

http://localhost:8080/info

Unlike when we tried localhost:8080/unknown, we will not receive a 404 this time. We have now created the info endpoint in our code, and the response we receive is:

{
  "app": "Demo Flask API",
  "author": "Your Name",
  "description": "This is a simple API built with Flask for demo purposes.",
  "version": "1.0"
}

In further guides, we will talk about how to develop API building skills out further. If you are interested in building a data API quickly and without code, while still harnessing the power of frameworks like Flask, you can check out our API builder by uploading a CSV below.

Gavin
Gavin