How to Create a RESTful API in Python with Flask

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Installation
  4. Creating a Flask Application
  5. Defining Routes
  6. Implementing CRUD Operations
  7. Handling Request Data
  8. Testing the API
  9. Conclusion

Introduction

In this tutorial, we will learn how to create a RESTful API in Python using the Flask framework. A RESTful API allows different software applications to communicate and exchange data over the web. We will create a simple API that performs CRUD (Create, Read, Update, Delete) operations on a resource.

By the end of this tutorial, you will be able to:

  • Set up a Flask application for creating a RESTful API
  • Define routes and handle HTTP methods
  • Implement CRUD operations for a resource
  • Test the API using tools like cURL or Postman

Prerequisites

Before you start this tutorial, you should have basic knowledge of Python programming language. Familiarity with the Flask framework is helpful but not mandatory.

Installation

To begin, you need to install Flask and its dependencies. Open your terminal and run the following command: pip install flask This will install Flask and its required packages.

Creating a Flask Application

Before we can create the API, let’s set up a basic Flask application. Create a new Python file, for example, app.py. ```python from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()
``` In the above code, we import the `Flask` class from the `flask` module. We create an instance of the `Flask` class and define a route for the root URL ("/"). When the root URL is accessed, the `hello()` function is called, which returns the string "Hello, World!".

Save the file and run it using the following command: python app.py You should see output similar to: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Congratulations! You have successfully created a Flask application.

Defining Routes

Routes allow us to define different URLs and associate them with specific functions. Let’s define some routes for our API.

In the app.py file, after the hello() function, add the following code: ```python @app.route(‘/api/users’, methods=[‘GET’]) def get_users(): # Logic for retrieving users return “List of users”

@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    # Logic for retrieving a specific user
    return f"User with ID {user_id}"
``` In the above code, we define two routes:
  1. /api/users - This route is associated with the get_users() function, which will retrieve a list of users.
  2. /api/users/<int:user_id> - This route is associated with the get_user(user_id) function, which will retrieve a specific user based on the provided user_id.

Note that we use the <int:user_id> syntax to indicate that the user_id parameter should be an integer.

Save the file and restart the Flask application. Now, if you access http://127.0.0.1:5000/api/users, you should see “List of users” displayed. Similarly, accessing http://127.0.0.1:5000/api/users/1 should display “User with ID 1”.

Implementing CRUD Operations

Now that we have defined the routes, let’s implement the CRUD operations for our API. We will use a simple in-memory list to store user data.

Add the following imports at the top of the app.py file: python from flask import request, jsonify In the existing get_users() function, modify it to return a JSON response instead of a string: python @app.route('/api/users', methods=['GET']) def get_users(): # Logic for retrieving users users = [ {'id': 1, 'name': 'John Doe'}, {'id': 2, 'name': 'Jane Smith'}, ] return jsonify(users) In the get_user(user_id) function, implement the logic to retrieve a specific user: ```python @app.route(‘/api/users/', methods=['GET']) def get_user(user_id): users = [ {'id': 1, 'name': 'John Doe'}, {'id': 2, 'name': 'Jane Smith'}, ]

    for user in users:
        if user['id'] == user_id:
            return jsonify(user)

    return jsonify({'error': 'User not found'})
``` Next, add the route and function for creating a new user:
```python
@app.route('/api/users', methods=['POST'])
def create_user():
    user = request.json
    # Logic for creating a new user
    return jsonify(user)
``` In the `create_user()` function, we retrieve the JSON data sent with the request using `request.json`. 

Similarly, add routes and functions for updating and deleting users: ```python @app.route(‘/api/users/', methods=['PUT']) def update_user(user_id): user = request.json # Logic for updating the user return jsonify(user)

@app.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    # Logic for deleting the user
    return jsonify({'message': 'User deleted'})
``` Save the file and restart the Flask application. Now our API supports all the CRUD operations for the `users` resource.

Handling Request Data

To test our API, we need a way to send HTTP requests with data. We can use tools like cURL or Postman. For simplicity, we’ll use cURL commands.

  1. To get a list of users:
     curl http://127.0.0.1:5000/api/users
    
  2. To get a specific user:
     curl http://127.0.0.1:5000/api/users/1
    
  3. To create a new user:
     curl -X POST -H "Content-Type: application/json" -d '{"name": "Alice"}' http://127.0.0.1:5000/api/users
    
  4. To update a user:
     curl -X PUT -H "Content-Type: application/json" -d '{"name": "Bob"}' http://127.0.0.1:5000/api/users/1
    
  5. To delete a user:
     curl -X DELETE http://127.0.0.1:5000/api/users/1
    

    Conclusion

In this tutorial, we have learned how to create a RESTful API in Python using the Flask framework. We started by setting up a basic Flask application and defining routes for different URLs. Then, we implemented the CRUD operations for a users resource, allowing us to create, read, update, and delete users. Finally, we tested the API using cURL commands.

Flask provides a simple and flexible way to create powerful APIs, and it is widely used in the web development community. With the knowledge gained from this tutorial, you can now create your own RESTful APIs in Python using Flask.