Fully featured framework for fast, easy and documented API development with Flask
npx @tessl/cli install tessl/pypi-flask-restplus@0.13.0A comprehensive extension for the Flask web framework that provides tools to rapidly build REST APIs with automatic documentation generation. Flask-RESTPlus offers a decorator-based approach for defining API endpoints, request/response marshalling with field validation, namespace organization for API structure, and built-in Swagger/OpenAPI documentation generation.
pip install flask-restplusfrom flask_restplus import Api, Resource, NamespaceCommon imports for API development:
from flask_restplus import Api, Resource, Namespace, fields, reqparse
from flask_restplus import marshal_with, marshal_with_field, abortAdditional imports for advanced features:
from flask_restplus import Model, OrderedModel, SchemaModel, Mask
from flask_restplus import RestError, ValidationError, SpecsError
from flask_restplus import Swagger, inputs, cors, apidocfrom flask import Flask
from flask_restplus import Api, Resource, fields
app = Flask(__name__)
api = Api(app, doc='/doc/')
# Define a model for request/response marshalling
todo_model = api.model('Todo', {
'id': fields.Integer(required=True, description='Task ID'),
'task': fields.String(required=True, description='Task description'),
'completed': fields.Boolean(description='Task completion status')
})
# Create a namespace
ns = api.namespace('todos', description='Todo operations')
@ns.route('/')
class TodoList(Resource):
@ns.marshal_list_with(todo_model)
def get(self):
"""List all todos"""
return [
{'id': 1, 'task': 'Build an API', 'completed': False},
{'id': 2, 'task': 'Write documentation', 'completed': True}
]
@ns.expect(todo_model)
@ns.marshal_with(todo_model, code=201)
def post(self):
"""Create a new todo"""
# Implementation would handle the request
return {'id': 3, 'task': 'New task', 'completed': False}, 201
if __name__ == '__main__':
app.run(debug=True)Flask-RESTPlus is built around several key components that work together to create RESTful APIs:
This design enables rapid API development with automatic documentation generation, comprehensive input validation, and structured error handling while maintaining Flask's flexibility and extensibility.
Core classes for creating RESTful APIs with automatic documentation, including the main Api class for Flask integration and Resource base class for endpoint definition.
class Api:
def __init__(self, app=None, **kwargs): ...
def add_resource(self, resource, *urls, **kwargs): ...
def namespace(self, name, **kwargs): ...
class Resource:
def __init__(self, api=None, *args, **kwargs): ...
def dispatch_request(self, *args, **kwargs): ...Data model definition and automatic marshalling system for request/response handling, including model classes and marshalling decorators.
class Model(dict):
def __init__(self, name, *args, **kwargs): ...
def marshal_with(fields, **kwargs): ...
def marshal(data, fields, **kwargs): ...Comprehensive field type system for validation, marshalling, and documentation generation, supporting strings, numbers, dates, nested objects, and custom validators.
class Raw: ...
class String(Raw): ...
class Integer(Raw): ...
class DateTime(Raw): ...
class Nested(Raw): ...
class List(Raw): ...Request parsing system for handling URL parameters, form data, JSON payloads, and file uploads with validation and type conversion.
class RequestParser:
def add_argument(self, name, **kwargs): ...
def parse_args(self, **kwargs): ...
class Argument:
def __init__(self, name, **kwargs): ...Pre-built validation functions for common input types including emails, URLs, IP addresses, dates, and custom regular expression patterns.
def email(value): ...
def url(value): ...
def ipv4(value): ...
def date(value): ...
def boolean(value): ...Structured error handling with HTTP status codes, custom exception classes, and automatic error response formatting.
def abort(code, message=None, **kwargs): ...
class RestError(Exception): ...
class ValidationError(RestError): ...Automatic API documentation generation with Swagger/OpenAPI support, including interactive documentation interface and specification export.
class Swagger:
def __init__(self, api): ...
def as_dict(self): ...
def ui_for(api): ...def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=False):
"""
Marshal data using field definitions.
Args:
data: The data to marshal
fields (dict): Field definitions for marshalling
envelope (str, optional): Envelope key for response wrapping
skip_none (bool): Skip None values in output
mask (str, optional): Field mask for partial responses
ordered (bool): Preserve field ordering
Returns:
dict: Marshalled data
"""
def marshal_with_field(field, **kwargs):
"""
Marshal return data with a single field.
Args:
field: Field instance for marshalling
envelope (str, optional): Envelope key for response wrapping
mask (str, optional): Field mask for partial responses
Returns:
function: Decorator function
"""
def abort(code=500, message=None, **kwargs):
"""
Abort request with HTTP error.
Args:
code (int): HTTP status code
message (str, optional): Error message
**kwargs: Additional error data
Raises:
HTTPException: Flask HTTP exception
"""Core model classes for data structure definition and validation, including ordered models and JSON schema support.
class Model(dict):
def __init__(self, name, *args, **kwargs): ...
def inherit(self, name, *parents): ...
def clone(self, name=None): ...
class OrderedModel(Model):
def __init__(self, name, *args, **kwargs): ...
class SchemaModel(Model):
def __init__(self, name, schema=None): ...Response field masking system for controlling API output and partial responses.
class Mask:
def __init__(self, mask=None, skip=False, **kwargs): ...
def apply(self, data): ...
def __str__(self): ...Additional exception classes for comprehensive error handling.
class SpecsError(RestError):
def __init__(self, msg): ...Advanced functionality modules.
# CORS support module
import cors
# API documentation utilities
import apidoc
# Swagger/OpenAPI specification generation
class Swagger:
def __init__(self, api): ...
def as_dict(self): ...__version__: str # Package version
__description__: str # Package description