Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Building RESTful APIs in Python using Flask

July 10, 2024

Building RESTful APIs in Python using Flask

Flask is a popular micro web framework written in Python, designed to build web applications with a simple and efficient approach. In this blog post, we will explore how to build RESTful APIs using Flask.

Setting up Flask

Before we begin, make sure you have Flask installed. You can install Flask using pip:

1
pip install flask

Creating a Flask App

To get started, let’s create a basic Flask application. Create a new Python file, app.py, and add the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from flask import Flask

app = Flask(__name__)

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

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

In this example, we import the Flask module and create a Flask application named app. The @app.route('/') decorator specifies the URL route for the index page. The hello() function is called when someone navigates to the root URL ("/") and returns the string “Hello, World!”. Finally, we run the Flask application using app.run().

You can now start the Flask application by running python app.py in your terminal. Navigate to http://localhost:5000 on your web browser, and you should see the message “Hello, World!”.

Creating an API Endpoint

Now that we have a basic Flask app up and running, let’s create an API endpoint to retrieve a list of users. Modify the app.py file as follows:

1
2
3
4
5
6
7
8
9
users = [
    {'id': 1, 'name': 'Alice'},
    {'id': 2, 'name': 'Bob'},
    {'id': 3, 'name': 'Charlie'}
]

@app.route('/api/users', methods=['GET'])
def get_users():
    return {'users': users}

In the modified code above, we created a list of users as a placeholder for a database. The get_users() function now handles the route “/api/users” and returns a dictionary containing the list of users.

Restart your Flask application and navigate to http://localhost:5000/api/users. You should see a JSON response containing the list of users:

1
2
3
4
5
6
7
{
    "users": [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"},
        {"id": 3, "name": "Charlie"}
    ]
}

Congratulations! You have just created your first RESTful API endpoint using Flask.

Implementing CRUD Operations

RESTful APIs typically support CRUD (Create, Read, Update, Delete) operations. Let’s implement these operations for our user API. Modify the app.py file to include the following functions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from flask import request

@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    for user in users:
        if user['id'] == user_id:
            return user
    return 'User not found', 404

@app.route('/api/users', methods=['POST'])
def create_user():
    new_user = request.get_json()
    users.append(new_user)
    return new_user, 201

@app.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    for user in users:
        if user['id'] == user_id:
            updated_user = request.get_json()
            user.update(updated_user)
            return user
    return 'User not found', 404

@app.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    for user in users:
        if user['id'] == user_id:
            users.remove(user)
            return 'User deleted'
    return 'User not found', 404

In the updated code above, we added four new functions to handle different HTTP methods (GET, POST, PUT, DELETE). The get_user() function retrieves a specific user by their ID. The create_user() function adds a new user to the list. The update_user() function updates an existing user. The delete_user() function removes a user from the list.

Make sure to import the request module from Flask to handle data sent with HTTP requests.

Now you can perform CRUD operations on the user API, interacting with the data through the different endpoints. For example, to create a new user, make a POST request to http://localhost:5000/api/users with the user data as the request body.

Conclusion

Flask provides a simple and flexible framework for building RESTful APIs in Python. In this blog post, we covered how to set up Flask, create API endpoints, and implement CRUD operations. Flask’s lightweight nature, combined with its excellent documentation, makes it an ideal choice for building APIs.

You can find the full source code for this example here.

Happy coding!


➡️ Introduction to ATmega-328 Microcontroller


⬅️ Exploring the Features of nRF52 SoC


Go back to Posts.