or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

api-resources.mddocumentation.mderror-handling.mdfields.mdindex.mdinput-validation.mdmodels-marshalling.mdrequest-parsing.md
tile.json

tessl/pypi-flask-restplus

Fully featured framework for fast, easy and documented API development with Flask

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/flask-restplus@0.13.x

To install, run

npx @tessl/cli install tessl/pypi-flask-restplus@0.13.0

index.mddocs/

Flask-RESTPlus

A 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.

Package Information

  • Package Name: flask-restplus
  • Package Type: Flask extension
  • Language: Python
  • Installation: pip install flask-restplus

Core Imports

from flask_restplus import Api, Resource, Namespace

Common imports for API development:

from flask_restplus import Api, Resource, Namespace, fields, reqparse
from flask_restplus import marshal_with, marshal_with_field, abort

Additional 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, apidoc

Basic Usage

from 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)

Architecture

Flask-RESTPlus is built around several key components that work together to create RESTful APIs:

  • Api: The main class that wraps a Flask app and provides API functionality
  • Resource: Base class for API endpoints (extends Flask's MethodView)
  • Namespace: Groups related resources together (similar to Flask Blueprints)
  • Models: Define data structures for request/response validation and documentation
  • Fields: Type system for validation, marshalling, and documentation
  • Marshalling: Automatic serialization of Python objects to JSON responses

This design enables rapid API development with automatic documentation generation, comprehensive input validation, and structured error handling while maintaining Flask's flexibility and extensibility.

Capabilities

API and Resource Management

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): ...

API and Resources

Models and Marshalling

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): ...

Models and Marshalling

Field Types

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): ...

Field Types

Request Parsing

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): ...

Request Parsing

Input Validation

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): ...

Input Validation

Error Handling

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): ...

Error Handling

Documentation and Swagger

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): ...

Documentation

Global Functions

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
    """

Advanced Components

Model Classes

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): ...

Field Masking

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): ...

Exception Classes

Additional exception classes for comprehensive error handling.

class SpecsError(RestError):
    def __init__(self, msg): ...

Core Modules

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): ...

Package Metadata

__version__: str  # Package version
__description__: str  # Package description