6.5. Flask-RESTful#
Flask-RESTful is an extension for Flask that helps you quickly build REST APIs. It adds helpful tools for:
Creating resources (API endpoints)
Handling HTTP methods (
GET,POST, etc.)Managing request data
Returning consistent JSON responses
Instead of writing everything manually with @app.route() and jsonify(), Flask-RESTful gives you a class-based structure that keeps your API logic modular and maintainable.
The main advantage of Flask-RESTful is that it reduces the amount of repetitive “boiler-plate” code that we need to write as developers.
6.5.1. Resources#
Each API endpoint is represented as a class with methods like get, post, put, and delete.
The example below:
creates a
BookResourcesubclassingResourceadds the
addmethod which accepts abook_idparameter
from flask_restful import Resource
class BookResource(Resource):
def get(self, book_id):
return {"id": book_id, "title": "Dune"}
Note
Notice that we can return a Python dictionary directly from get and Flask-RESTful will handle serialising the dictionary for us.
6.5.2. Routing#
Instead of using @app.route(), you register resource classes with an Api object.
In the example below:
we create
apian instance ofApiwe register the
BookResourceclass as the handler for the URL'/api/books/<int:book_id>'
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
api.add_resource(BookResource, '/api/books/<int:book_id>')
6.5.3. Request Parameter Parsing#
Flask-RESTful comes with a class RequestParser to read the parameters from the current Flask request context and make them available inside the Resource methods.
To configure a parser:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('title', required=True)
parser.add_argument('author', required=True)
To use a parser:
args = parser.parse_args()
print(args['title'])
print(args['author'])