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.
Features of Flask-RESTful:
- Simplifies API Development – Provides a cleaner and more structured approach.
- Automatic Request Parsing – Built-in support for handling request arguments.
- Better Resource Management – Uses classes to define API resources.
- Response Formatting – Automatically formats responses in JSON.
- Integrated Error Handling – Provides built-in exception handling for common errors.
Installation and Setup
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
How Flask-RESTful Works
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.
Resource Class
- Resource is a special class provided by Flask-RESTful.
- When a class (like GFG, in the example below) inherits from Resource, it automatically gains the ability to handle HTTP methods (GET, POST, PUT, DELETE).
- We define these methods inside the class, and Flask-RESTful automatically maps them to the corresponding API requests.
Key concepts in Flask-RESTful:
- Resource Class – Each API resource is defined as a class that inherits from Resource.
- Methods for HTTP Requests – get(), post(), put(), and delete() methods handle different HTTP requests.
- Adding Resources to API – The add_resource() method links resource classes to specific URL endpoints.
Before we build a full-fledged API, let’s look at a basic example:
Python
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
# Defining a simple resource
class GFG(Resource):
def get(self):
return {"message": "Hello, Flask-RESTful!"}
# Adding resource to API
api.add_resource(GFG, '/')
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- We create a GFG class that inherits from Resource.
- The get() method returns a JSON response when a GET request is made.
- The add_resource() method links the GFG resource to the '/' route.
Now if we run the app we can see the message:
Restful APIBuilding a REST API with Flask-RESTful
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:
- Get all books
- Get a specific book by ID
- Add a new book
- Update an existing book
- Delete a book
Here is the implementation:
Python
from flask import Flask, request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
# Sample data
books = [
{"id": 1, "title": "Concept of Physics", "author": "H.C Verma"},
{"id": 2, "title": "Gunahon ka Devta", "author": "Dharamvir Bharti"},
{"id": 3, "title": "Problems in General Physics", "author": "I.E Irodov"}
]
# API Resource Class
class BookResource(Resource):
def get(self, book_id=None):
if book_id is None:
return books, 200 # Explicitly return status 200
book = next((book for book in books if book["id"] == book_id), None)
if book:
return book, 200 # Explicitly return 200 OK
return {"error": "Book not found"}, 404 # Return 404 only when not found
def post(self):
new_book = request.json
books.append(new_book)
return new_book, 201 # Created status
def put(self, book_id):
book = next((book for book in books if book["id"] == book_id), None)
if not book:
return {"error": "Book not found"}, 404 # Explicit 404
data = request.json
book.update(data)
return book, 200 # Return updated book with 200 OK
def delete(self, book_id):
global books
books = [book for book in books if book["id"] != book_id]
return {"message": "Book deleted"}, 200 # Explicitly return 200
# Adding Resources to API
api.add_resource(BookResource, '/books', '/books/<int:book_id>')
if __name__ == '__main__':
app.run(debug=True)
Explanation:
1. Flask-RESTful Setup
- Api(app): Initializes the REST API.
- api.add_resource(): Registers the resource class to specific endpoints.
2. Understanding API Methods:
- GET /books – Returns the complete list of books.
- GET /books/<book_id> – Retrieves details of a single book by ID.
- POST /books – Adds a new book to the list.
- PUT /books/<book_id> – Updates an existing book’s information.
- DELETE /books/<book_id> – Removes a book from the list
Running and Testing Application
Launch the Flask application using this command in termial:
python app.py
After the app is live on development server, open the Postman app to test the API Methods:
GET all Books:
Make a GET Request to URL- http://127.0.0.1:5000/books:
GET MethodGET a specific book:
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.
GET Method for a specific bookPOST a New Book
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:
POST MethodDELETE a Book
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).
DELETE MethodSimilary 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 |
---|
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read