Simple API using Flask

amalshaji profile image Amal Shaji ・3 min read

In this post, we are creating a simple API(Application Programming Interface). For those who don't know, an API is a simple way to connect two different programs/services. For example, you could use slack api to send messages to slack directly from the program that you're working on.

Here we use Flask to create an API. Flask is a micro web framework for python to create dynamic webpages. Flask is simple to use and easy to learn. It is one of the top 5 frameworks used for creating API's and other endpoints. This tutorial is simple and you could learn flask on the go.

For this whole experiment let's say our flask server is running on localhost:5000(default for flask)

Let's import all the necessary packages required.

from flask import Flask, jsonify
import uuid
import time

app = Flask(__name__)

user_data = dict()

Here we import Flask and jsonify from flask. Jsonify is used to return response in json format. uuid stands for Universally unique identifier and is used to create a unique api key for every username. time is used because our api returns current time. app variable is initialized with out Flask app. Now we use this app to create endpoints. user_data is a dictionary that contains username: api_key. We use a dictionary because it's a simple example. For a bigger job, use databases like mongodb or redis.

Flask requires every endpoint to be associated with a method. An endpoint is simple a url that the server can understand. A method is a function to call when the url is reached.

def homepage():
    return "homepage"

Here "/" is the endpoint and when "/" is reached(http://localhost:5000/), the function homepage executes return "hompage". Now let's add a endpoint to create an api_key.

@app.route("/create/<username>", methods=["POST"])
def create(username):
    if username not in user_data:
        api_key = str(uuid.uuid4())[:8]
        user_data[username] = api_key
        data = {
            "username": username,
            "api_key": api_key,
            "message": "api_key created",
            "status_code": 200,
        data = {"message": "username already exists", "status_code": 404}
    return jsonify(data)

Here the endpoint is http://localhost:5000/create/<username>. The function create takes the username, check if it's unique and then assigns a unique api_key to it. The username:api_key pair is now stored in user_data.

@app.route("/<api_key>", methods=["POST"])
def verify(api_key):
    if api_key in user_data.values():
        data = {"message": "api connection successful", "status_code": 200}
        data = {"message": "api_key not valid", "status_code": 404}
    return jsonify(data)

This is a simple method to check if the api_key we have is valid or the endpoint is up and running.

@app.route("/api/<api_key>", methods=["POST"])
def data(api_key):
    if api_key in user_data.values():
        data = {"data": str(time.ctime()), "message": "success", "status_code": 200}
        data = {"message": "api_key not valid", "status_code": 404}
    return jsonify(data)

This method is the usage of api. When we call the api with valid api_key, is returns the current time. You could replace the logic with your own code to make the api do something else. In all these methods, the data returned is in json format. Json is structured and easy to interpret. Last, we need to run the server.

if __name__ == "__main__":

The server is running and you could use cURL or postman to make post requests. Example of running the api is given below. Now that you have created a simple API, you could go deep and add features like rate limiting(limit the number of API calls), add password based authentication and API expiry.



Editor guide