CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-restplus

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

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

fields.mddocs/

Field Types

Comprehensive field type system for validation, marshalling, and documentation generation. Flask-RESTPlus provides a rich set of field types for handling different data formats including strings, numbers, dates, nested objects, and custom validators.

Capabilities

Base Field Classes

Foundation classes that provide common functionality for all field types.

class Raw:
    def __init__(self, default=None, attribute=None, title=None, description=None, 
                 required=False, readonly=False, example=None, **kwargs):
        """
        Base field class for all other fields.
        
        Args:
            default: Default value if field is missing
            attribute (str, optional): Source attribute name if different from field name
            title (str, optional): Field title for documentation
            description (str, optional): Field description for documentation
            required (bool): Whether field is required
            readonly (bool): Whether field is read-only
            example: Example value for documentation
            **kwargs: Additional field options
        """
    
    def format(self, value):
        """
        Format the field value for output.
        
        Args:
            value: Raw field value
        
        Returns:
            Formatted value
        """
    
    def output(self, key, obj, **kwargs):
        """
        Extract and format field value from an object.
        
        Args:
            key (str): Field key
            obj: Source object
            **kwargs: Additional options
        
        Returns:
            Formatted field value
        """

class StringMixin:
    def __init__(self, min_length=None, max_length=None, **kwargs):
        """
        Mixin for string-based validation.
        
        Args:
            min_length (int, optional): Minimum string length
            max_length (int, optional): Maximum string length
            **kwargs: Additional field options
        """

class MinMaxMixin:
    def __init__(self, min=None, max=None, **kwargs):
        """
        Mixin for min/max constraints.
        
        Args:
            min: Minimum value
            max: Maximum value
            **kwargs: Additional field options
        """

class NumberMixin(MinMaxMixin):
    def __init__(self, **kwargs):
        """
        Mixin for numeric field validation.
        
        Args:
            **kwargs: Additional field options including min/max
        """

String Fields

Field types for handling text data with various formatting and validation options.

class String(StringMixin, Raw):
    def __init__(self, enum=None, discriminator=None, **kwargs):
        """
        String field with validation options.
        
        Args:
            enum (list, optional): List of allowed values
            discriminator (str, optional): Discriminator property for polymorphism
            **kwargs: Additional string field options (min_length, max_length, etc.)
        """

class FormattedString(StringMixin, Raw):
    def __init__(self, src_str, **kwargs):
        """
        String field with format string support.
        
        Args:
            src_str (str): Format string (e.g., "Hello {name}")
            **kwargs: Additional string field options
        """

class ClassName(String):
    def __init__(self, dash=False, **kwargs):
        """
        String field that converts to class name format.
        
        Args:
            dash (bool): Use dash-case instead of camelCase
            **kwargs: Additional string field options
        """

Numeric Fields

Field types for handling numeric data with precision control and range validation.

class Integer(NumberMixin, Raw):
    def __init__(self, **kwargs):
        """
        Integer field with range validation.
        
        Args:
            **kwargs: Additional numeric field options (min, max, etc.)
        """

class Float(NumberMixin, Raw):
    def __init__(self, **kwargs):
        """
        Float field with range validation.
        
        Args:
            **kwargs: Additional numeric field options (min, max, etc.)
        """

class Arbitrary(NumberMixin, Raw):
    def __init__(self, **kwargs):
        """
        Arbitrary precision decimal field.
        
        Args:
            **kwargs: Additional numeric field options (min, max, etc.)
        """

class Fixed(NumberMixin, Raw):
    def __init__(self, decimals=5, **kwargs):
        """
        Fixed precision decimal field.
        
        Args:
            decimals (int): Number of decimal places
            **kwargs: Additional numeric field options (min, max, etc.)
        """

Date and Time Fields

Field types for handling temporal data with various format support.

class DateTime(MinMaxMixin, Raw):
    def __init__(self, dt_format='iso8601', **kwargs):
        """
        DateTime field with format support.
        
        Args:
            dt_format (str): Date format ('iso8601', 'rfc822', or custom format)
            **kwargs: Additional datetime field options (min, max, etc.)
        """

class Date(DateTime):
    def __init__(self, **kwargs):
        """
        Date-only field (no time component).
        
        Args:
            **kwargs: Additional date field options
        """

Boolean and URL Fields

Fields for handling boolean values and URL validation.

class Boolean(Raw):
    def __init__(self, **kwargs):
        """
        Boolean field that accepts various true/false representations.
        
        Args:
            **kwargs: Additional field options
        """

class Url(StringMixin, Raw):
    def __init__(self, endpoint=None, absolute=False, scheme=None, **kwargs):
        """
        URL field with validation and URL generation support.
        
        Args:
            endpoint (str, optional): Flask endpoint for URL generation
            absolute (bool): Generate absolute URLs
            scheme (str, optional): URL scheme for absolute URLs
            **kwargs: Additional URL field options
        """

Complex Fields

Field types for handling nested data structures and collections.

class Nested(Raw):
    def __init__(self, model, allow_null=False, skip_none=False, **kwargs):
        """
        Nested model field for embedding other models.
        
        Args:
            model (dict or Model): Nested model definition
            allow_null (bool): Allow null values
            skip_none (bool): Skip None values in nested object
            **kwargs: Additional nested field options
        """

class List(Raw):
    def __init__(self, cls_or_instance, **kwargs):
        """
        List field for arrays of values.
        
        Args:
            cls_or_instance (Field): Field type for list items
            **kwargs: Additional list field options
        """

class Polymorph(Nested):
    def __init__(self, mapping, required=False, **kwargs):
        """
        Polymorphic field that selects model based on discriminator.
        
        Args:
            mapping (dict): Mapping from discriminator values to models
            required (bool): Whether field is required
            **kwargs: Additional polymorphic field options
        """

class Wildcard(Raw):
    def __init__(self, **kwargs):
        """
        Field that accepts any additional properties not defined in model.
        
        Args:
            **kwargs: Additional wildcard field options
        """

Field Validation Error

Exception class for field marshalling and validation errors.

class MarshallingError(Exception):
    def __init__(self, underlying_exception):
        """
        Exception raised during field marshalling.
        
        Args:
            underlying_exception (Exception): The underlying exception that caused the error
        """

Usage Examples

Basic Field Usage

from flask_restplus import Api, fields

api = Api()

# Simple fields
simple_model = api.model('Simple', {
    'id': fields.Integer(required=True, description='Unique identifier'),
    'name': fields.String(required=True, min_length=1, max_length=100),
    'active': fields.Boolean(default=True),
    'score': fields.Float(min=0.0, max=100.0),
    'website': fields.Url(),
    'created_at': fields.DateTime(dt_format='iso8601')
})

String Field Variations

from flask_restplus import Api, fields

api = Api()

string_examples = api.model('StringExamples', {
    # Basic string
    'name': fields.String(required=True),
    
    # String with length constraints
    'username': fields.String(min_length=3, max_length=20),
    
    # String with allowed values (enum)
    'status': fields.String(enum=['active', 'inactive', 'pending']),
    
    # Formatted string
    'greeting': fields.FormattedString('Hello {name}!'),
    
    # Class name formatting
    'css_class': fields.ClassName(dash=True),  # converts to dash-case
    
    # String with example and description
    'description': fields.String(
        description='Item description',
        example='A high-quality product'
    )
})

Numeric Field Examples

from flask_restplus import Api, fields

api = Api()

numeric_model = api.model('Numeric', {
    # Integer with range
    'age': fields.Integer(min=0, max=150),
    
    # Float with precision
    'price': fields.Float(min=0.0),
    
    # Fixed decimal (for currency, etc.)
    'amount': fields.Fixed(decimals=2),
    
    # Arbitrary precision for very large numbers
    'big_number': fields.Arbitrary(),
    
    # Required numeric fields
    'quantity': fields.Integer(required=True, min=1)
})

Date and Time Fields

from flask_restplus import Api, fields

api = Api()

datetime_model = api.model('DateTime', {
    # ISO8601 datetime (default)
    'created_at': fields.DateTime(),
    
    # RFC822 datetime
    'updated_at': fields.DateTime(dt_format='rfc822'),
    
    # Custom datetime format
    'custom_date': fields.DateTime(dt_format='%Y-%m-%d %H:%M:%S'),
    
    # Date only (no time)
    'birth_date': fields.Date(),
    
    # DateTime with range constraints
    'event_date': fields.DateTime(
        min=datetime(2023, 1, 1),
        max=datetime(2024, 12, 31)
    )
})

Nested and Complex Fields

from flask_restplus import Api, fields

api = Api()

# Address model for nesting
address_model = api.model('Address', {
    'street': fields.String(required=True),
    'city': fields.String(required=True),
    'country': fields.String(required=True),
    'postal_code': fields.String()
})

# User model with nested address
user_model = api.model('User', {
    'id': fields.Integer(required=True),
    'name': fields.String(required=True),
    
    # Nested model
    'address': fields.Nested(address_model),
    
    # Optional nested model
    'billing_address': fields.Nested(address_model, allow_null=True),
    
    # List of strings
    'tags': fields.List(fields.String),
    
    # List of nested models
    'addresses': fields.List(fields.Nested(address_model)),
    
    # List with validation
    'scores': fields.List(fields.Float(min=0, max=100))
})

Advanced Field Features

from flask_restplus import Api, fields

api = Api()

# Custom attribute mapping
user_model = api.model('User', {
    'id': fields.Integer(required=True),
    'full_name': fields.String(attribute='name'),  # Maps to 'name' in source data
    'user_email': fields.String(attribute='email.primary'),  # Nested attribute access
})

# Read-only fields
response_model = api.model('Response', {
    'id': fields.Integer(readonly=True),  # Won't be used for input validation
    'created_at': fields.DateTime(readonly=True),
    'name': fields.String(required=True)
})

# Fields with examples for documentation
documented_model = api.model('Documented', {
    'name': fields.String(
        required=True,
        description='User full name',
        example='John Doe'
    ),
    'age': fields.Integer(
        min=0,
        max=150,
        description='User age in years',
        example=25
    )
})

Polymorphic Fields

from flask_restplus import Api, fields

api = Api()

# Base animal model
animal_model = api.model('Animal', {
    'name': fields.String(required=True),
    'type': fields.String(required=True, discriminator=True)
})

# Dog specific model
dog_model = api.inherit('Dog', animal_model, {
    'breed': fields.String(required=True),
    'good_boy': fields.Boolean(default=True)
})

# Cat specific model  
cat_model = api.inherit('Cat', animal_model, {
    'lives_remaining': fields.Integer(min=0, max=9, default=9),
    'attitude': fields.String(enum=['friendly', 'aloof', 'evil'])
})

# Model that can contain different animal types
zoo_model = api.model('Zoo', {
    'name': fields.String(required=True),
    'animals': fields.List(fields.Polymorph({
        'dog': dog_model,
        'cat': cat_model
    }))
})

Field Validation Handling

from flask_restplus import Api, Resource, fields, marshal_with

api = Api()

user_model = api.model('User', {
    'name': fields.String(required=True, min_length=2),
    'age': fields.Integer(min=0, max=150),
    'email': fields.String(required=True)
})

@api.route('/users')
class UserList(Resource):
    @api.expect(user_model, validate=True)  # Enable validation
    @api.marshal_with(user_model)
    def post(self):
        # Validation errors will be automatically handled
        # Invalid data will return 400 Bad Request with error details
        data = api.payload
        # Process validated data...
        return data, 201

Wildcard Fields

from flask_restplus import Api, fields

api = Api()

# Model that accepts additional properties
flexible_model = api.model('Flexible', {
    'id': fields.Integer(required=True),
    'name': fields.String(required=True),
    # Accept any additional properties
    '*': fields.Wildcard()
})

# Usage: can include any additional fields beyond id and name
# {"id": 1, "name": "Test", "custom_field": "value", "another": 123}

Install with Tessl CLI

npx tessl i tessl/pypi-flask-restplus

docs

api-resources.md

documentation.md

error-handling.md

fields.md

index.md

input-validation.md

models-marshalling.md

request-parsing.md

tile.json