{"id":4030,"date":"2023-11-04T23:14:00","date_gmt":"2023-11-04T23:14:00","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-rest-api-with-flask-restful-and-python\/"},"modified":"2023-11-05T05:48:24","modified_gmt":"2023-11-05T05:48:24","slug":"how-to-build-a-rest-api-with-flask-restful-and-python","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-rest-api-with-flask-restful-and-python\/","title":{"rendered":"How to Build a REST API with Flask Restful and Python"},"content":{"rendered":"
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.<\/p>\n
To follow along with this tutorial, you will need the following:<\/p>\n
pip install flask flask-restful<\/code> command)<\/li>\n<\/ul>\nSetting up the Project<\/h2>\n
First, let’s create a new directory for our project. Open your terminal (or command prompt) and run the following command:<\/p>\n
mkdir flask-rest-api-tutorial\ncd flask-rest-api-tutorial\n<\/code><\/pre>\nNext, 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:<\/p>\n
python3 -m venv venv\nsource venv\/bin\/activate\n<\/code><\/pre>\nNow, let’s create a new file called app.py<\/code> in the project directory. Open the file in your favorite text editor and let’s start building our REST API.<\/p>\nCreating the Flask Application<\/h2>\n
In the app.py<\/code> file, import the necessary modules and create a Flask app object. Add the following code:<\/p>\nfrom flask import Flask\nfrom flask_restful import Api\n\napp = Flask(__name__)\napi = Api(app)\n\nif __name__ == '__main__':\n app.run(debug=True)\n<\/code><\/pre>\nIn the above code, we import the Flask<\/code> class from the flask<\/code> module and the Api<\/code> class from the flask_restful<\/code> module. We then create a Flask app object and an API object, passing the app object as an argument to the API constructor.<\/p>\nThe line if __name__ == '__main__':<\/code> ensures that the app only runs if the app.py<\/code> file is executed directly (not imported as a module).<\/p>\nCreating the API Resources<\/h2>\n
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<\/code> that returns a “Hello, World!” message.<\/p>\nBelow the app and API object declarations, add the following code:<\/p>\n
class HelloWorld(Resource):\n def get(self):\n return {'message': 'Hello, World!'}\n\napi.add_resource(HelloWorld, '\/')\n<\/code><\/pre>\nIn the above code, we define a class called HelloWorld<\/code> that inherits from the Resource<\/code> class provided by Flask Restful. Inside the HelloWorld<\/code> class, we define a get<\/code> method that returns a dictionary containing a message.<\/p>\nThe line api.add_resource(HelloWorld, '\/')<\/code> associates the HelloWorld<\/code> resource with the root URL path (“\/”) of our API.<\/p>\nRunning the Application<\/h2>\n
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<\/code> file:<\/p>\napi.add_resource(HelloWorld, '\/')\n\nif __name__ == '__main__':\n app.run(debug=True)\n<\/code><\/pre>\nNow, in your terminal, run the following command to start the Flask development server:<\/p>\n
python app.py\n<\/code><\/pre>\nIf everything is set up correctly, you should see output similar to the following:<\/p>\n
* Running on http:\/\/127.0.0.1:5000\/ (Press CTRL+C to quit)\n<\/code><\/pre>\nYou can open your web browser and navigate to `http:\/\/127.0.0.1:5000\/` to see the “Hello, World!” message.<\/p>\n
Testing the API<\/h2>\n
Now that our API is up and running, let’s test it using a tool like curl<\/code> or a REST client like Postman.<\/p>\nOpen a new terminal window and run the following command to make a GET request to the root URL of the API:<\/p>\n
curl http:\/\/127.0.0.1:5000\/\n<\/code><\/pre>\nYou should see the following response:<\/p>\n
{\n \"message\": \"Hello, World!\"\n}\n<\/code><\/pre>\nCongratulations! You have successfully built a simple RESTful API using Flask Restful and Python.<\/p>\n
Adding More Functionality to the API<\/h2>\n
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.<\/p>\n
Below the HelloWorld<\/code> class definition, add the following code:<\/p>\nclass TodoList(Resource):\n todos = []\n\n def get(self):\n return {'todos': self.todos}\n\n def post(self):\n data = request.get_json()\n new_todo = {'id': len(self.todos) + 1, 'task': data['task']}\n self.todos.append(new_todo)\n return new_todo, 201\n\napi.add_resource(TodoList, '\/todos')\n<\/code><\/pre>\nIn the above code, we define a new class called TodoList<\/code> that also inherits from the Resource<\/code> class. This class has a class variable todos<\/code> which is an empty list that will hold the todo items.<\/p>\nThe get<\/code> method returns a dictionary containing all the todo items. The post<\/code> method retrieves the data from the request payload, creates a new todo item with an auto-incremented ID, adds it to the todos<\/code> list, and returns the newly created todo item along with the HTTP status code 201.<\/p>\nWe then add the TodoList<\/code> resource to the \/todos<\/code> URL of our API.<\/p>\nTesting the Updated API<\/h2>\n
Let’s test the updated API using curl or a REST client.<\/p>\n
First, restart the Flask development server by pressing Ctrl+C<\/code> in the terminal and running python app.py<\/code> again.<\/p>\nNow, open a new terminal window and run the following command to make a POST request to the \/todos<\/code> URL with some data:<\/p>\ncurl -X POST -H \"Content-Type: application\/json\" -d '{\"task\":\"Buy groceries\"}' http:\/\/127.0.0.1:5000\/todos\n<\/code><\/pre>\nYou should see the following response:<\/p>\n
{\n \"id\": 1,\n \"task\": \"Buy groceries\"\n}\n<\/code><\/pre>\nTo retrieve all the todos, run the following command:<\/p>\n
curl http:\/\/127.0.0.1:5000\/todos\n<\/code><\/pre>\nYou should see the following response:<\/p>\n
{\n \"todos\": [\n {\n \"id\": 1,\n \"task\": \"Buy groceries\"\n }\n ]\n}\n<\/code><\/pre>\nYou can repeat the above steps to create more todo items and retrieve the updated list.<\/p>\n
Conclusion<\/h2>\n
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.<\/p>\n
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.<\/p>\n
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.<\/p>\n","protected":false},"excerpt":{"rendered":"
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: Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[926,929,407,457,927,925,75,928,49,316,924],"yoast_head":"\nHow to Build a REST API with Flask Restful and Python - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n