Registry / web-framework / flask-restful

flask-restful

JSON →
library0.3.10pypypi✓ verified 23d ago

Flask-RESTful is an extension for Flask that simplifies the creation of REST APIs by providing building blocks like Resources for organizing endpoints and `reqparse` for input validation. The current stable version is 0.3.10, released in May 2023. While still available, the project appears to be in maintenance mode with infrequent updates and hasn't seen major feature releases since 2014.

pip install flask-restful
INSTALL
IMPORT
SIG · FLASK-RESTFUL
F
flask-restful
web-frameworkpythonv0.3.10
Install
2.5s avg
Import
485ms
Disk
25MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.3.10 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.492s · 26.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.5s · import 0.478s · 27MB
25MB installed
● package 25MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Api
from flask_restful import Api
Main class for Flask-RESTful API initialization.
Resource
from flask_restful import Resource
Base class for defining API endpoints.
reqparse
from flask_restful import reqparse
Module for parsing and validating request arguments.

This quickstart demonstrates how to create a simple Flask-RESTful API. It defines two resources: one for a 'Hello, World!' message at the root path and another to calculate the square of an integer at `/square/<num>`. To run, save as `app.py` and execute `python app.py`. Access `http://127.0.0.1:5000/` for the greeting or `http://127.0.0.1:5000/square/5` for the square calculation.

from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def get(self): return {'message': 'Hello, World!'} class Square(Resource): def get(self, num): return {'square': num**2} api.add_resource(HelloWorld, '/') api.add_resource(Square, '/square/<int:num>') if __name__ == '__main__': app.run(debug=True)
Debug
Known issues
breakingFlask-RESTful may encounter breaking issues or unexpected behavior with Flask versions 2.3 and newer, specifically due to changes in its underlying `werkzeug` dependency. Some unit tests may fail, indicating potential compatibility problems.
fix
Consider using an older Flask version (e.g., <2.3) if encountering issues, or explore alternative API frameworks like Flask-RESTX which is built on Flask-RESTful and offers more active maintenance and features. If staying with Flask-RESTful, monitor its GitHub issues for potential patches related to newer Flask versions.
affects: Flask >= 2.3
gotchaThe `flask-restful` project has seen limited development and maintenance activity since 2014, despite a recent version bump. Users seeking more active development, modern features (like auto-generated documentation via Swagger UI), or better compatibility with the latest Python/Flask ecosystems might find it lacking.
fix
For new projects or if advanced features and active maintenance are crucial, consider using Flask-RESTX, which is a successor to Flask-RESTful and provides additional capabilities like Swagger documentation and namespaces.
affects: <= 0.3.10
gotchaWhile Flask-RESTful supports dependency injection by allowing arguments to be passed to resource constructors via `add_resource()`, it does not provide a built-in, sophisticated dependency injection framework.
fix
Developers may need to implement their own manual dependency injection or integrate a separate dependency injection library if a more robust solution is required. Alternatives like FastAPI offer built-in dependency injection.
affects: All versions
gotchaThe PyPI classifiers for `flask-restful` still list compatibility with Python 2.7, which is end-of-life and no longer officially supported by the Python community. Developing new applications with Python 2.7 is strongly discouraged.
fix
Ensure your project runs on Python 3.x. While Flask-RESTful 0.3.10 is compatible with Python 3.x, relying on a library that still officially lists Python 2.7 support might indicate dated design considerations.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'flask_restful'
The Flask-RESTful library is not installed in the Python environment, or the environment where it's installed is not the one being used to run the application.
fix
Ensure `flask-restful` is installed using pip in your active Python environment. If using a virtual environment, activate it first.
`pip install Flask-RESTful` or `pip3 install Flask-RESTful`
AttributeError: type object 'YourResourceName' has no attribute 'as_view'
This error typically occurs when attempting to register a Flask-RESTful `Resource` class with Flask's `add_url_rule` or similar method, or when the `Api` object is initialized or resources are added to it before a Flask application instance is properly associated with it. It can also be caused by naming conflicts between a Flask-RESTful Resource and other objects.
fix
Ensure you are using `api.add_resource(YourResourceName, '/your_endpoint')` to register resources with the `Api` object, and that the `Api` object is properly initialized with your Flask app instance (e.g., `api = Api(app)`). Do not manually call `as_view()` on your `Resource` class. If the error persists, check for naming collisions.

```python
from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)
```
werkzeug.exceptions.BadRequest: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
This often happens when `reqparse` fails to validate incoming request arguments, typically due to missing required arguments, incorrect data types, or the client sending data without the `Content-Type: application/json` header for JSON payloads.
fix
Verify that the client sends the correct `Content-Type` header (e.g., `application/json` for JSON data) and that all required arguments are provided with the correct types. If using `reqparse`, explicitly define the `location` for arguments if they are not in the default `flask.Request.values` or `flask.Request.json`.

```python
from flask import Flask
from flask_restful import reqparse, Api, Resource

app = Flask(__name__)
api = Api(app)

class Todo(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('task', type=str, required=True, help='Task cannot be blank!')
        # For arguments from URL query string, specify location='args'
        # parser.add_argument('user_id', type=int, location='args')
        args = parser.parse_args()
        return {'status': 'success', 'task': args['task']}

api.add_resource(Todo, '/todo')

if __name__ == '__main__':
    app.run(debug=True)
```
TypeError: Object of type 'YourObject' is not JSON serializable
Flask-RESTful attempts to convert the return value of a resource method to a JSON response, but the returned object is not a JSON-serializable type (e.g., a custom class instance, a SQLAlchemy model object, or a `flask.Response` object itself).
fix
Ensure that your resource methods return dictionaries, lists, or other JSON-serializable types. If returning custom objects, you need to serialize them manually (e.g., convert them to a dictionary) or use Flask-RESTful's `marshal_with` decorator with `fields` to define how the object should be serialized.

```python
from flask import Flask
from flask_restful import Api, Resource, fields, marshal_with

app = Flask(__name__)
api = Api(app)

# Example of a non-serializable object
class User:
    def __init__(self, id, name):
        self.id = id
        self.name = name

# Define how a User object should be marshalled (serialized)
user_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'uri': fields.Url('user_detail')  # Example for generating a URL
}

class UserDetail(Resource):
    @marshal_with(user_fields)
    def get(self, user_id):
        # In a real app, this would fetch from a database
        user = User(user_id, f'User {user_id}')
        return user

api.add_resource(UserDetail, '/users/<int:user_id>', endpoint='user_detail')

if __name__ == '__main__':
    app.run(debug=True)
```
Upgrade
Version history
0.3.10latest on PyPI · released May 21, 2023
Audit
Dependencies
FlaskrequiredCore web framework dependency.
aniso8601requiredUsed for ISO 8601 date parsing and formatting.
pytzrequiredUsed for timezone definitions and handling.
sixrequiredPython 2 and 3 compatibility utilities.
Agent activity
8 hits · last 30 days
node
6
Amazon
1
Resources
flask-restful — pip install flask-restful · libregistry