![]() |
VOOZH | about |
Flask-RESTful is an extension for Flask that simplifies the process of building REST APIs. It provides additional tools for creating APIs with minimal boilerplate code while following REST principles. With Flask-RESTful, defining API resources, handling requests, and formatting responses become more structured and efficient.
Create a project folder and then inside that folder create and activate a virtual environment to install Flask and other necessary modules in it. Use these commands to create and activate a new virtual environment:
python -m venv venv
.venv\Scripts\activate
And after that install Flask and Flask-RESTful extension using these command:
pip install flask
pip install flask-restful
Flask-RESTful simplifies API development by introducing a class-based approach. Instead of defining routes using @app.route(), Flask-RESTful allows us to define API resources as Python classes, where each HTTP method (GET, POST, PUT, DELETE) is represented by a class method.
Before we build a full-fledged API, letβs look at a basic example:
Explanation:
Now if we run the app we can see the message:
Now that we understand the basics, let's move on to building a complete REST API that manages a collection of books. Our API will allow users to:
Here is the implementation:
Explanation:
1. Flask-RESTful Setup
2. Understanding API Methods:
Launch the Flask application using this command in termial:
python app.pyAfter the app is live on development server, open the Postman app to test the API Methods:
Make a GET Request to URL- http://127.0.0.1:5000/books:
Make a GET Request to URL- http://127.0.0.1:5000/books/id , replace the id with the desired book id for example, to get the book with id=3, URL should be - http://127.0.0.1:5000/books/3.
Make a POST Request to URL- http://127.0.0.1:5000/books, and provide the book data in JSON format under the raw tab:
To delete a book, a DELETE request with the book id should be made to the URL- http://127.0.0.1:5000/books/id (replace the id with the specific book id).
Similary we can test all the different methods using Postman app, below is a table that summarizes how to make different request with their specific configurations.
| Action | Method | URL | Body (JSON) | Response |
|---|---|---|---|---|
| Get all books | GET | /books | None | List of books |
| Get a book by ID | GET | /books/1 | None | Book details or 404 |
| Add a new book | POST | /books | { "id": 4, "title": "New", "author": "X" } | New book data |
| Update a book | PUT | /books/2 | { "title": "Updated" } | Updated book data or 404 |