Create your own Flask API in Python: A Step-by-Step Guide

Image that you are working on a project and you develop a creative and an amazing tool using Python that can save significant amount of time. Now you want to make this software available to the world and thinking about how to do so? This is where Flask API comes into play.

Application Programming Interface, or API, is a bridge that is responsible for communication between two application. Very well-known examples for this are the third-party apps for social media that provide different types of information and are used for multiple purposes. They use APIs of the respective social media sites, and send and receive information via APIs. While this analogy could be used to understand the basic meaning of an API, we still need to be a bit nerdy and understand its technical meaning.

So today in this step-by-step guide on creating a RESTful API with Flask in Python, we will understand how APIs work and how they function. Later on, we will create our very own API using Python and deploy it on our local server.

Have a look at this blog where I used OpenWeather API to create a small Python project:
https://machinelearningsite.com/creating-a-weather-app-in-python/

flask api
Photo by Designecologist on Pexels.com

What is an API?

An API, which stands for Application Programming Interface, is a set of rules and protocols that allows different software applications to communicate and interact with each other. It serves as an intermediary that enables the exchange of data and functionalities between various software systems, allowing them to work together seamlessly. But the beauty of APIs goes beyond their role as mere intermediaries. They encourage innovation, motivate developers to create new and creative applications and services by harnessing the functionalities of existing ones. It’s akin to having a treasure trove of building blocks to craft something entirely new and exciting.

The range of use-cases of APIs is wide , some of which include:

  1. Web Services: Web services need data that is necessary for their functionality. APIs are the tool that provide them with the necessary data. To add to the analogy of social media mentioned earlier, platforms offer APIs that allow developers to integrate features like sharing posts or retrieving user information into their own applications.
  2. Integration: Businesses use APIs to connect different software systems within their organization, such as linking a customer relationship management (CRM) system with an email marketing platform to automate communication.
  3. Third-Party Plugins: Many software applications use APIs to get data and trigger further events accordingly. My weather application project serves as a good example of this. According to the data I received via the API, I created events that sent alerts to me in case of a bad weather.
  4. Mobile Apps: Mobile app developers use APIs to access device features like the camera, location services, or push notifications.

Now that we have basic understanding of what an API is, we can start with the coding part.

The Code

Creating a Python API is a comprehensive task and follows a particular pipeline. We will go through each of them and understand the corresponding process:

1. Choosing a Framework

A framework can be considered a template or set of rules that can be modified based on our needs while building software. Some of the most popular frameworks available for Python are

  1. Django REST.
  2. Flask RESTful.
  3. FastAPI.
  4. Pyramid.
  5. Falcon.
  6. Bottle.
  7. Eve.
  8. Sanic.

For this project, we will use Flask which is known for its simplicity. Flask is a lightweight and flexible micro-framework for Python that makes it easy to create APIs.

2. Create a virtual environment

It is always a good coding practice to build your software in a virtual environment. Virtual environments allow you to create isolated environments for different Python projects. This means that you can have different sets of packages and dependencies for each project, ensuring that they don’t interfere with each other. This is particularly crucial when you’re working on multiple projects with varying requirements.

Let us say we want to name our virtual environment as ‘app-env’. We can create the same by:

python3 -m virtualenv app-env

Now that we have our environment created, we need to source it so that all of our dependencies are installed in this virtual environment.

cd app-env
source bin/activate

3. Install Flask

Now that we are in our ‘app-env’, we will create our application in this env. If you haven’t already, you’ll need to install Flask. You can do this using pip:

pip3 install Flask

After installing Flask, create a file and name it app.py. Copy the following code and paste it in the file.

from flask import Flask, jsonify, request

app = Flask(__name__)

# Sample data (you can replace this with your own data source)
data = [
    {"id": 1, "name": "Item 1"},
    {"id": 2, "name": "Item 2"},
    {"id": 3, "name": "Item 3"}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(data)

@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = next((item for item in data if item['id'] == item_id), None)
    if item is None:
        return jsonify({"message": "Item not found"}), 404
    return jsonify(item)

@app.route('/api/items', methods=['POST'])
def create_item():
    new_item = request.get_json()
    data.append(new_item)
    return jsonify(new_item), 201

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

Let us break this code down and understand it step-by-step:

Importing dependencies

from flask import Flask, jsonify

Here, we import two important modules from the Flask framework:

  • Flask: This module allows us to create a Flask web application.
  • jsonify: This module is used to convert Python dictionaries into JSON format, which is commonly used for API responses.
  • request: This module provides access to the incoming HTTP request data, allowing us to read data sent to the server.

Creating a Flask Instance:

app = Flask(__name__)

We create a Flask web application instance by initializing the Flask class. The __name__ argument is a special Python variable that tells Flask where to look for templates and static files.

Creating a Python dictionary to store data

data = [
    {"id": 1, "name": "Item 1"},
    {"id": 2, "name": "Item 2"},
    {"id": 3, "name": "Item 3"}
]

This is sample data that represents a collection of items. In a real application, this data would typically come from a database or some external source.

Defining a Route to Get All Items

@app.route('/api/items', methods=['GET'])

This route definition tells Flask to execute the get_items function when a client makes a GET request to the /api/items URL.

Creating a Route Handler Function to Get All Items

def get_items():
    return jsonify(data)

We then create a route handler function to get all items. The get_items function returns the entire data list as a JSON response when the /api/items route is accessed with a GET request.

Defining a Route to Get a Single Item

@app.route('/api/items/<int:item_id>', methods=['GET'])

This route definition includes a parameter <int:item_id> in the URL, which allows us to access a specific item by its ID.

Creating a Route Handler Function to Get a Single Item

def get_item(item_id):
    item = next((item for item in data if item['id'] == item_id), None)
    if item is None:
        return jsonify({"message": "Item not found"}), 404
    return jsonify(item)

Next, we create a route handler function to get a single item. The get_item function takes the item_id from the URL and retrieves the corresponding item from the data list. If the item is not found, it returns a JSON response with a “Item not found” message and a 404 status code (Not Found).

Defining a Route to Create an Item:

@app.route('/api/items', methods=['POST'])

We proceed further to define a route to create an item. This route definition tells Flask to execute the create_item function when a client makes a POST request to the /api/items URL.

Creating a Route Handler Function to Create an Item

def create_item():
    new_item = request.get_json()
    data.append(new_item)
    return jsonify(new_item), 201

Then, we create a route handler function to create an item. The create_item function reads the JSON data sent in the request using request.get_json(), adds the new item to the data list, and returns a JSON response with the newly created item and a 201 status code (Created).

Running the Flask Application

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

Ultimately, we run the Flask application. This conditional block ensures that the Flask application only runs if the script is executed directly (not imported as a module). When you run the script, Flask’s development web server is started, and the application begins listening for incoming HTTP requests. The debug=True argument is optional but helpful during development, as it provides more detailed error messages.

4. Run your App

Save this code to a Python file (e.g. app.py) and run it. Your API will be accessible http://localhost:5000.

python app.py

Voila! Now you have your own Python API running on your localhost. Feel free to play around with the code and your own custom functions, for example a site that answers user’s query using ChatGPT or converting an RGB image into grayscale. Happy coding!

Leave a Reply