Flask-RESTful
Flask-RESTful is an extension that adds REST API support to Flask. It provides Resource classes that map HTTP methods to Python functions, input parsing, a...
Building REST APIs with Flask-RESTful
Flask-RESTful is an extension that adds REST API support to Flask. It provides Resource classes that map HTTP methods to Python functions, input parsing, and output formatting, reducing boilerplate compared to plain Flask routes.
Install with pip install flask-restful. Basic setup: from flask import Flask from flask_restful import Api, Resource
app = Flask(__name__) api = Api(app)
class HelloWorld(Resource): def get(self): return {'message': 'Hello, World!'}
api.add_resource(HelloWorld, '/hello')
if __name__ == '__main__': app.run(debug=True)
A complete CRUD Resource for articles: from flask_restful import Resource, reqparse, abort
articles_db = {}
def abort_if_not_found(article_id): if article_id not in articles_db: abort(404, message=f'Article {article_id} not found')
parser = reqparse.RequestParser() parser.add_argument('title', required=True, help='Title is required') parser.add_argument('content', required=True)
class ArticleResource(Resource): def get(self, article_id): abort_if_not_found(article_id) return articles_db[article_id]
def post(self, article_id): args = parser.parse_args() articles_db[article_id] = {'title': args['title'], 'content': args['content']} return articles_db[article_id], 201
def delete(self, article_id): abort_if_not_found(article_id) del articles_db[article_id] return '', 204
api.add_resource(ArticleResource, '/articles/<int:article_id>')
The reqparse module validates and parses request arguments: parser.add_argument('page', type=int, default=1, location='args') # from query string parser.add_argument('Authorization', location='headers') # from headers
Output fields with marshal_with control what data is returned: from flask_restful import fields, marshal_with
article_fields = { 'id': fields.Integer, 'title': fields.String, 'url': fields.Url('article_endpoint') }
class ArticleList(Resource): @marshal_with(article_fields) def get(self): return Article.query.all()
Practical tip: For production REST APIs in Flask, consider flask-smorest or FastAPI instead of Flask-RESTful. Flask-RESTful's reqparse is deprecated in favor of marshmallow for validation, which provides better error messages and schema-based validation.
Exam tip: Flask-RESTful automatically serializes Python dictionaries and lists to JSON responses. It also maps HTTP method names (get, post, put, delete) to Resource class methods by name convention, not by decorator.