How to Build a REST API with Flask Restful and Python

In this tutorial, we will learn how to build a RESTful API using Flask Restful, a Flask extension that simplifies the process of building APIs in Flask. We will use Python as the programming language for this tutorial.

Prerequisites

To follow along with this tutorial, you will need the following:

  • Python 3 installed on your machine
  • Flask and Flask Restful libraries installed (you can install them using pip install flask flask-restful command)

Setting up the Project

First, let’s create a new directory for our project. Open your terminal (or command prompt) and run the following command:

mkdir flask-rest-api-tutorial
cd flask-rest-api-tutorial

Next, we’ll create a virtual environment for our project. This is an isolated Python environment where we can install all the required dependencies without affecting the global Python installation. Run the following commands to create and activate the virtual environment:

python3 -m venv venv
source venv/bin/activate

Now, let’s create a new file called app.py in the project directory. Open the file in your favorite text editor and let’s start building our REST API.

Creating the Flask Application

In the app.py file, import the necessary modules and create a Flask app object. Add the following code:

from flask import Flask
from flask_restful import Api

app = Flask(__name__)
api = Api(app)

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

In the above code, we import the Flask class from the flask module and the Api class from the flask_restful module. We then create a Flask app object and an API object, passing the app object as an argument to the API constructor.

The line if __name__ == '__main__': ensures that the app only runs if the app.py file is executed directly (not imported as a module).

Creating the API Resources

In a RESTful API, resources are the main objects that are exposed through the API. We can think of resources as the objects we want to manipulate or interact with. In our example, let’s create a simple resource called HelloWorld that returns a “Hello, World!” message.

Below the app and API object declarations, add the following code:

class HelloWorld(Resource):
    def get(self):
        return {'message': 'Hello, World!'}

api.add_resource(HelloWorld, '/')

In the above code, we define a class called HelloWorld that inherits from the Resource class provided by Flask Restful. Inside the HelloWorld class, we define a get method that returns a dictionary containing a message.

The line api.add_resource(HelloWorld, '/') associates the HelloWorld resource with the root URL path (“/”) of our API.

Running the Application

Before we run the application, we need to tell Flask which routes are available in our API. To do this, we need to add the following code to the end of the app.py file:

api.add_resource(HelloWorld, '/')

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

Now, in your terminal, run the following command to start the Flask development server:

python app.py

If everything is set up correctly, you should see output similar to the following:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

You can open your web browser and navigate to `http://127.0.0.1:5000/` to see the “Hello, World!” message.

Testing the API

Now that our API is up and running, let’s test it using a tool like curl or a REST client like Postman.

Open a new terminal window and run the following command to make a GET request to the root URL of the API:

curl http://127.0.0.1:5000/

You should see the following response:

{
    "message": "Hello, World!"
}

Congratulations! You have successfully built a simple RESTful API using Flask Restful and Python.

Adding More Functionality to the API

So far, our API only responds to GET requests and returns a fixed message. Let’s add more functionality by creating a new resource that accepts POST requests and allows us to store and retrieve data.

Below the HelloWorld class definition, add the following code:

class TodoList(Resource):
    todos = []

    def get(self):
        return {'todos': self.todos}

    def post(self):
        data = request.get_json()
        new_todo = {'id': len(self.todos) + 1, 'task': data['task']}
        self.todos.append(new_todo)
        return new_todo, 201

api.add_resource(TodoList, '/todos')

In the above code, we define a new class called TodoList that also inherits from the Resource class. This class has a class variable todos which is an empty list that will hold the todo items.

The get method returns a dictionary containing all the todo items. The post method retrieves the data from the request payload, creates a new todo item with an auto-incremented ID, adds it to the todos list, and returns the newly created todo item along with the HTTP status code 201.

We then add the TodoList resource to the /todos URL of our API.

Testing the Updated API

Let’s test the updated API using curl or a REST client.

First, restart the Flask development server by pressing Ctrl+C in the terminal and running python app.py again.

Now, open a new terminal window and run the following command to make a POST request to the /todos URL with some data:

curl -X POST -H "Content-Type: application/json" -d '{"task":"Buy groceries"}' http://127.0.0.1:5000/todos

You should see the following response:

{
    "id": 1,
    "task": "Buy groceries"
}

To retrieve all the todos, run the following command:

curl http://127.0.0.1:5000/todos

You should see the following response:

{
    "todos": [
        {
            "id": 1,
            "task": "Buy groceries"
        }
    ]
}

You can repeat the above steps to create more todo items and retrieve the updated list.

Conclusion

In this tutorial, we have learned how to build a RESTful API using Flask Restful and Python. We started by setting up the project and creating a Flask application. Then we created a simple resource that returns a “Hello, World!” message. We tested the API using curl and learned how to add more functionality to the API by creating another resource that accepts POST requests and allows us to store and retrieve data.

Flask Restful is a powerful and flexible tool for building RESTful APIs with Flask. It provides a clean and easy-to-use interface for defining resources and handling HTTP methods. With Flask Restful, you can quickly build complex APIs with minimal code and effort.

You can further explore Flask Restful by adding more features to this API, such as updating and deleting resources, implementing authentication and authorization, and handling error responses. The official Flask Restful documentation is a great resource for learning more about the capabilities and features of this library.

Related Post