CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-restx

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

Pending
Overview
Eval results
Files

marshalling-fields.mddocs/

Response Marshalling and Fields

Flask-RESTX provides a comprehensive type system for defining response schemas with automatic serialization, validation, and documentation generation. The fields system supports primitive and complex data structures with extensive configuration options for data transformation and validation.

Capabilities

Marshalling Functions

Core functions for data serialization using field definitions.

def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=False):
    """
    Serialize data using field definitions.

    Parameters:
    - data: Raw data (dict, list, object) to serialize
    - fields: Dictionary of field definitions for serialization
    - envelope: Optional key to wrap serialized response
    - skip_none: Whether to skip None values in output
    - mask: Field mask for selective serialization
    - ordered: Whether to preserve field order

    Returns:
    dict or OrderedDict: Serialized data
    """

def marshal_with(fields, **kwargs):
    """
    Decorator for automatic response marshalling.

    Parameters:
    - fields: Field definitions or model for marshalling
    - envelope: Optional envelope key
    - skip_none: Skip None values
    - mask: Field mask
    - ordered: Preserve order

    Returns:
    Decorator function
    """

def marshal_with_field(field, **kwargs):
    """
    Decorator for marshalling with a single field.

    Parameters:
    - field: Single field definition
    - kwargs: Additional marshalling options

    Returns:
    Decorator function
    """

Base Field Classes

Foundation classes that other fields extend.

class Raw:
    def __init__(
        self,
        default=None,
        attribute=None,
        title=None,
        description=None,
        required=False,
        readonly=False,
        example=None,
        mask=None
    ):
        """
        Base field class with no formatting.

        Parameters:
        - default: Default value if field is missing
        - attribute: Source attribute name (if different from field name)
        - title: Field title for documentation
        - description: Field description for documentation
        - required: Whether field is required
        - readonly: Whether field is read-only (documentation only)
        - example: Example value for documentation
        - mask: Optional mask function for output transformation
        """

    def format(self, value):
        """Format the field value."""

    def output(self, key, obj, ordered=False):
        """Extract and format value from source object."""

class StringMixin:
    """Mixin providing string validation functionality."""

    def __init__(self, **kwargs):
        """Additional string-specific parameters like min_length, max_length, pattern."""

class MinMaxMixin:
    """Mixin providing min/max validation for numeric fields."""

    def __init__(self, min_val=None, max_val=None, **kwargs):
        """
        Parameters:
        - min_val: Minimum allowed value
        - max_val: Maximum allowed value
        """

class NumberMixin(MinMaxMixin):
    """Mixin providing number-specific validation."""

Primitive Field Types

Fields for basic data types with validation and formatting.

class String(StringMixin, Raw):
    def __init__(
        self,
        enum=None,
        discriminator=None,
        min_length=None,
        max_length=None,
        pattern=None,
        **kwargs
    ):
        """
        String field with validation.

        Parameters:
        - enum: List of allowed string values
        - discriminator: Property name used for polymorphism
        - min_length: Minimum string length
        - max_length: Maximum string length
        - pattern: Regular expression pattern
        - kwargs: Base field parameters
        """

class Integer(NumberMixin, Raw):
    def __init__(
        self,
        min=None,
        max=None,
        exclusiveMin=None,
        exclusiveMax=None,
        multiple=None,
        **kwargs
    ):
        """
        Integer field with range validation.

        Parameters:
        - min: Minimum value (inclusive)
        - max: Maximum value (inclusive)
        - exclusiveMin: Minimum value (exclusive)
        - exclusiveMax: Maximum value (exclusive)
        - multiple: Value must be multiple of this number
        - kwargs: Base field parameters
        """

class Float(NumberMixin, Raw):
    def __init__(
        self,
        min=None,
        max=None,
        exclusiveMin=None,
        exclusiveMax=None,
        multiple=None,
        **kwargs
    ):
        """
        Float field with range validation.

        Parameters:
        - min: Minimum value (inclusive)
        - max: Maximum value (inclusive)
        - exclusiveMin: Minimum value (exclusive)
        - exclusiveMax: Maximum value (exclusive)
        - multiple: Value must be multiple of this number
        - kwargs: Base field parameters
        """

class Boolean(Raw):
    def __init__(self, **kwargs):
        """Boolean field that converts various inputs to bool."""

class DateTime(Raw):
    def __init__(
        self,
        dt_format='iso8601',
        min=None,
        max=None,
        **kwargs
    ):
        """
        DateTime field with format conversion.

        Parameters:
        - dt_format: Output format ('iso8601', 'rfc822', or custom format string)
        - min: Minimum datetime
        - max: Maximum datetime
        - kwargs: Base field parameters
        """

class Date(Raw):
    def __init__(self, min=None, max=None, **kwargs):
        """
        Date field (date only, no time component).

        Parameters:
        - min: Minimum date
        - max: Maximum date
        - kwargs: Base field parameters
        """

class Arbitrary(NumberMixin, Raw):
    def __init__(
        self,
        min=None,
        max=None,
        exclusiveMin=None,
        exclusiveMax=None,
        multiple=None,
        **kwargs
    ):
        """
        Field for arbitrary precision numbers (Decimal).

        Parameters:
        - min: Minimum value (inclusive)
        - max: Maximum value (inclusive)
        - exclusiveMin: Minimum value (exclusive)
        - exclusiveMax: Maximum value (exclusive)
        - multiple: Value must be multiple of this number
        - kwargs: Base field parameters
        """

class Fixed(NumberMixin, Raw):
    def __init__(
        self,
        decimals=5,
        min=None,
        max=None,
        exclusiveMin=None,
        exclusiveMax=None,
        multiple=None,
        **kwargs
    ):
        """
        Fixed precision decimal field.

        Parameters:
        - decimals: Number of decimal places
        - min: Minimum value (inclusive)
        - max: Maximum value (inclusive)
        - exclusiveMin: Minimum value (exclusive)
        - exclusiveMax: Maximum value (exclusive)
        - multiple: Value must be multiple of this number
        - kwargs: Base field parameters
        """

Complex Field Types

Fields for structured data and relationships.

class List(Raw):
    def __init__(
        self,
        cls_or_instance,
        min_items=None,
        max_items=None,
        unique=None,
        **kwargs
    ):
        """
        List/array field containing other fields.

        Parameters:
        - cls_or_instance: Field type for list items
        - min_items: Minimum number of items
        - max_items: Maximum number of items  
        - unique: Whether items must be unique
        - kwargs: Base field parameters
        """

class Nested(Raw):
    def __init__(
        self,
        model,
        allow_null=False,
        skip_none=False,
        as_list=False,
        **kwargs
    ):
        """
        Nested object field using other field definitions.

        Parameters:
        - model: Dictionary of nested field definitions or Model
        - allow_null: Whether to allow null values
        - skip_none: Whether to skip None values in nested object
        - as_list: Whether to treat nested field as list
        - kwargs: Base field parameters
        """

class Url(StringMixin, Raw):
    def __init__(
        self,
        endpoint=None,
        absolute=False,
        scheme=None,
        **kwargs
    ):
        """
        URL field with endpoint resolution.

        Parameters:
        - endpoint: Flask endpoint name for URL generation
        - absolute: Whether to generate absolute URLs
        - scheme: URL scheme override
        - kwargs: Base field parameters
        """

class FormattedString(StringMixin, Raw):
    def __init__(self, src_str, **kwargs):
        """
        String field with format template.

        Parameters:
        - src_str: Format string template (e.g., "Hello {name}")
        - kwargs: Base field parameters
        """

class ClassName(String):
    def __init__(self, dash=False, **kwargs):
        """
        Field that outputs the class name of the object.

        Parameters:
        - dash: Whether to convert CamelCase to dash-case
        - kwargs: String field parameters
        """

class Polymorph(Nested):
    def __init__(self, mapping, **kwargs):
        """
        Polymorphic field that chooses nested schema based on discriminator.

        Parameters:
        - mapping: Dictionary mapping discriminator values to schemas
        - kwargs: Nested field parameters
        """

class Wildcard(Raw):
    def __init__(self, cls_or_instance, **kwargs):
        """
        Field for arbitrary key-value pairs (dictionary passthrough).

        Parameters:
        - cls_or_instance: Field class or instance for wildcard values
        - kwargs: Base field parameters
        """

Field Utility Functions

Helper functions for field operations.

def get_value(key, obj, default=None):
    """
    Extract value from object using key (string, callable, or dot notation).

    Parameters:
    - key: Key to extract (string path, callable, or integer index)
    - obj: Source object
    - default: Default value if key not found

    Returns:
    Extracted value or default
    """

def to_marshallable_type(obj):
    """
    Convert object to marshallable dictionary.

    Parameters:
    - obj: Object to convert

    Returns:
    dict or original object if already marshallable
    """

def is_indexable_but_not_string(obj):
    """Check if object is indexable but not a string."""

def is_integer_indexable(obj):
    """Check if object supports integer indexing."""

Marshalling Exceptions

Exception types for marshalling errors.

class MarshallingError(RestError):
    def __init__(self, underlying_exception):
        """
        Exception raised during field marshalling.

        Parameters:
        - underlying_exception: Original exception that caused marshalling failure
        """

Usage Examples

Basic Field Usage

from flask_restx import fields, marshal

# Define field schema
user_fields = {
    'id': fields.Integer,
    'name': fields.String(required=True),
    'email': fields.String,
    'active': fields.Boolean(default=True),
    'created_at': fields.DateTime(dt_format='iso8601')
}

# Sample data
user_data = {
    'id': 1,
    'name': 'John Doe',
    'email': 'john@example.com',
    'active': True,
    'created_at': datetime.now()
}

# Marshal data
result = marshal(user_data, user_fields)

Advanced Field Configuration

# Field with validation and documentation
price_field = fields.Float(
    min_val=0.0,
    max_val=10000.0,
    description='Product price in USD',
    example=29.99,
    required=True
)

# String field with pattern validation
sku_field = fields.String(
    min_length=3,
    max_length=20,
    pattern=r'^[A-Z0-9-]+$',
    description='Product SKU code',
    example='PROD-123'
)

Nested Objects

# Address schema
address_fields = {
    'street': fields.String(required=True),
    'city': fields.String(required=True),
    'country': fields.String(required=True),
    'postal_code': fields.String
}

# User schema with nested address
user_fields = {
    'name': fields.String(required=True),
    'email': fields.String,
    'address': fields.Nested(address_fields)
}

user_data = {
    'name': 'Jane Smith',
    'email': 'jane@example.com',
    'address': {
        'street': '123 Main St',
        'city': 'Anytown',
        'country': 'USA',
        'postal_code': '12345'
    }
}

result = marshal(user_data, user_fields)

List Fields

# List of primitive values
tags_field = fields.List(fields.String)

# List of nested objects
comments_field = fields.List(fields.Nested({
    'id': fields.Integer,
    'text': fields.String,
    'author': fields.String,
    'created_at': fields.DateTime
}))

post_fields = {
    'title': fields.String,
    'content': fields.String,
    'tags': tags_field,
    'comments': comments_field
}

URL Fields

# URL field with endpoint resolution
user_url_field = fields.Url('user_detail', absolute=True)

# Fields referencing Flask endpoints
user_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'url': fields.Url('user_detail'),  # Generates URL to user_detail endpoint
    'avatar_url': fields.Url('user_avatar', absolute=True)
}

Decorator Usage

from flask_restx import Resource, marshal_with

class UserList(Resource):
    @marshal_with(user_fields)
    def get(self):
        # Return raw data, automatic marshalling applied
        return [
            {'id': 1, 'name': 'John', 'email': 'john@example.com'},
            {'id': 2, 'name': 'Jane', 'email': 'jane@example.com'}
        ]

    @marshal_with(user_fields, envelope='user')
    def post(self):
        # Response wrapped in envelope: {'user': {...}}
        new_user = {'id': 3, 'name': 'Bob', 'email': 'bob@example.com'}
        return new_user, 201

Field Masking

# Selective field serialization using masks
from flask_restx import Mask

# Only include specific fields
mask = Mask('name,email')
result = marshal(user_data, user_fields, mask=mask)

# Nested field masking
mask = Mask('name,address{city,country}')
result = marshal(user_data, user_fields, mask=mask)

Custom Field Attributes

# Using different source attribute
user_fields = {
    'id': fields.Integer,
    'display_name': fields.String(attribute='full_name'),  # Maps to full_name attribute
    'is_admin': fields.Boolean(attribute='admin_flag')
}

# Custom transformation with callable
def format_phone(obj):
    return f"({obj.area_code}) {obj.number}"

user_fields = {
    'phone': fields.String(attribute=format_phone)
}

Install with Tessl CLI

npx tessl i tessl/pypi-flask-restx

docs

core-api.md

error-handling.md

index.md

marshalling-fields.md

models-validation.md

request-parsing.md

tile.json