InputFilter

Overview

The InputFilter class is the core component of flask-inputfilter that provides data validation, filtering, and serialization capabilities for Flask applications. It supports two different approaches for defining input filters.

class flask_inputfilter.input_filter.InputFilter(methods=None)

Bases: object

Base class for all input filters.

Parameters:

methods (Optional[list[str]])

is_valid()

Checks if the object’s state or its attributes meet certain conditions to be considered valid. This function is typically used to ensure that the current state complies with specific requirements or rules.

Returns:

Returns True if the state or attributes of the object fulfill

all required conditions; otherwise, returns False.

Return type:

bool

classmethod validate()

Decorator for validating input data in routes.

Parameters:

cls

Returns:

Callable

Return type:

Callable

validate_data(data=None)

Validates input data against defined field rules, including applying filters, validators, custom logic steps, and fallback mechanisms. The validation process also ensures the required fields are handled appropriately and conditions are checked after processing.

Parameters:

data (dict[str, Any]) – A dictionary containing the input data to be validated where keys represent field names and values represent the corresponding data.

Returns:

A dictionary containing the

validated data with any modifications, default values, or processed values as per the defined validation rules.

Return type:

Union[dict[str, Any], Type[T]]

Raises:

Any errors raised during external API calls, validation, or – logical steps execution of the respective fields or conditions will propagate without explicit handling here.

add_condition(condition)

Add a condition to the input filter.

Parameters:

condition (BaseCondition) – The condition to add.

Return type:

None

get_conditions()

Retrieve the list of all registered conditions.

This function provides access to the conditions that have been registered and stored. Each condition in the returned list is represented as an instance of the BaseCondition type.

Returns:

A list containing all currently registered

instances of BaseCondition.

Return type:

list[BaseCondition]

set_data(data)

Filters and sets the provided data into the object’s internal storage, ensuring that only the specified fields are considered and their values are processed through defined filters.

Parameters:

data (dict[str, Any]) – The input dictionary containing key-value pairs where keys represent field names and values represent the associated data to be filtered and stored.

Return type:

None

get_value(name)

This method retrieves a value associated with the provided name. It searches for the value based on the given identifier and returns the corresponding result. If no value is found, it typically returns a default or fallback output. The method aims to provide flexibility in retrieving data without explicitly specifying the details of the underlying implementation.

Parameters:

name (str) – A string that represents the identifier for which the corresponding value is being retrieved. It is used to perform the lookup.

Returns:

The retrieved value associated with the given name. The

specific type of this value is dependent on the implementation and the data being accessed.

Return type:

Any

get_values()

Retrieves a dictionary of key-value pairs from the current object. This method provides access to the internal state or configuration of the object in a dictionary format, where keys are strings and values can be of various types depending on the object’s design.

Returns:

A dictionary containing string keys and their

corresponding values of any data type.

Return type:

dict[str, Any]

get_raw_value(name)

Fetches the raw value associated with the provided key.

This method is used to retrieve the underlying value linked to the given key without applying any transformations or validations. It directly fetches the raw stored value and is typically used in scenarios where the raw data is needed for processing or debugging purposes.

Parameters:

name (str) – The name of the key whose raw value is to be retrieved.

Returns:

The raw value associated with the provided key.

Return type:

Any

get_raw_values()

Retrieves raw values from a given source and returns them as a dictionary.

This method is used to fetch and return unprocessed or raw data in the form of a dictionary where the keys are strings, representing the identifiers, and the values are of any data type.

Returns:

A dictionary containing the raw values retrieved.

The keys are strings representing the identifiers, and the values can be of any type, depending on the source being accessed.

Return type:

dict[str, Any]

get_unfiltered_data()

Fetches unfiltered data from the data source.

This method retrieves data without any filtering, processing, or manipulations applied. It is intended to provide raw data that has not been altered since being retrieved from its source. The usage of this method should be limited to scenarios where unprocessed data is required, as it does not perform any validations or checks.

Returns:

The unfiltered, raw data retrieved from the

data source. The return type may vary based on the specific implementation of the data source.

Return type:

dict[str, Any]

set_unfiltered_data(data)

Sets unfiltered data for the current instance. This method assigns a given dictionary of data to the instance for further processing. It updates the internal state using the provided data.

Parameters:

data (dict[str, Any]) – A dictionary containing the unfiltered data to be associated with the instance.

Return type:

None

has_unknown()

Checks whether any values in the current data do not have corresponding configurations in the defined fields.

Returns:

True if there are any unknown fields; False otherwise.

Return type:

bool

get_error_message(field_name)

Retrieves and returns a predefined error message.

This method is intended to provide a consistent error message to be used across the application when an error occurs. The message is predefined and does not accept any parameters. The exact content of the error message may vary based on specific implementation, but it is designed to convey meaningful information about the nature of an error.

Parameters:

field_name (str) – The name of the field for which the error message is being retrieved.

Returns:

A string representing the predefined error message.

Return type:

Optional[str]

get_error_messages()

Retrieves all error messages associated with the fields in the input filter.

This method aggregates and returns a dictionary of error messages where the keys represent field names, and the values are their respective error messages.

Returns:

A dictionary containing field names as keys and

their corresponding error messages as values.

Return type:

dict[str, str]

add(name, required=False, default=None, fallback=None, filters=None, validators=None, steps=None, external_api=None, copy=None)

Add the field to the input filter.

Parameters:
  • name (str) – The name of the field.

  • required (Optional[bool]) – Whether the field is required.

  • default (Optional[Any]) – The default value of the field.

  • fallback (Optional[Any]) – The fallback value of the field, if validations fails or field None, although it is required.

  • filters (Optional[list[BaseFilter]]) – The filters to apply to the field value.

  • validators (Optional[list[BaseValidator]]) – The validators to apply to the field value.

  • steps (Optional[list[Union[BaseFilter, BaseValidator]]]) – Allows to apply multiple filters and validators in a specific order.

  • external_api (Optional[ExternalApiConfig]) – Configuration for an external API call.

  • copy (Optional[str]) – The name of the field to copy the value from.

Return type:

None

has(field_name)

This method checks the existence of a specific field within the input filter values, identified by its field name. It does not return a value, serving purely as a validation or existence check mechanism.

Parameters:

field_name (str) – The name of the field to check for existence.

Returns:

True if the field exists in the input filter,

otherwise False.

Return type:

bool

get_input(field_name)

Represents a method to retrieve a field by its name.

This method allows fetching the configuration of a specific field within the object, using its name as a string. It ensures compatibility with various field names and provides a generic return type to accommodate different data types for the fields.

Parameters:

field_name (str) – A string representing the name of the field who needs to be retrieved.

Returns:

The field corresponding to the

specified name.

Return type:

Optional[FieldModel]

get_inputs()

Retrieve the dictionary of input fields associated with the object.

Returns:

Dictionary containing field names as

keys and their corresponding FieldModel instances as values

Return type:

dict[str, FieldModel]

remove(field_name)

Removes the specified field from the instance or collection.

This method is used to delete a specific field identified by its name. It ensures the designated field is removed entirely from the relevant data structure. No value is returned upon successful execution.

Parameters:

field_name (str) – The name of the field to be removed.

Returns:

The value of the removed field, if any.

Return type:

Any

count()

Counts the total number of elements in the collection.

This method returns the total count of elements stored within the underlying data structure, providing a quick way to ascertain the size or number of entries available.

Returns:

The total number of elements in the collection.

Return type:

int

replace(name, required=False, default=None, fallback=None, filters=None, validators=None, steps=None, external_api=None, copy=None)

Replaces a field in the input filter.

Parameters:
  • name – The name of the field.

  • required (bool)

  • default (Any)

  • fallback (Any)

  • filters (Optional[list[BaseFilter]])

  • validators (Optional[list[BaseValidator]])

  • steps (Optional[list[Union[BaseFilter, BaseValidator]]])

  • external_api (Optional[ExternalApiConfig])

  • copy (Optional[str])

Return type:

None

add_global_filter(filter)

Add a global filter to be applied to all fields.

Parameters:

filter (BaseFilter) – The filter to add.

Return type:

None

get_global_filters()

Retrieve all global filters associated with this InputFilter instance.

This method returns a list of BaseFilter instances that have been added as global filters. These filters are applied universally to all fields during data processing.

Returns:

A list of global filters.

Return type:

list[BaseFilter]

clear()

Resets all fields of the InputFilter instance to their initial empty state.

This method clears the internal storage of fields, conditions, filters, validators, and data, effectively resetting the object as if it were newly initialized.

Return type:

None

merge(other)

Merges another InputFilter instance intelligently into the current instance.

  • Fields with the same name are merged recursively if possible,

    otherwise overwritten.

  • Conditions are combined and duplicated.

  • Global filters and validators are merged without duplicates.

Parameters:

other (InputFilter) – The InputFilter instance to merge.

Return type:

None

set_model(model_class)

Set the model class for serialization.

Parameters:

model_class (Type[T]) – The class to use for serialization.

Return type:

None

add_global_validator(validator)

Add a global validator to be applied to all fields.

Parameters:

validator (BaseValidator) – The validator to add.

Return type:

None

get_global_validators()

Retrieve all global validators associated with this InputFilter instance.

This method returns a list of BaseValidator instances that have been added as global validators. These validators are applied universally to all fields during validation.

Returns:

A list of global validators.

Return type:

list[BaseValidator]

Defining InputFilters

The declarative API uses Python decorators to define fields, conditions, and global filters/validators directly in the class definition.

from flask_inputfilter import InputFilter
from flask_inputfilter.declarative import field, condition, global_filter, global_validator
from flask_inputfilter.filters import StringTrimFilter
from flask_inputfilter.validators import IsStringValidator, LengthValidator
from flask_inputfilter.conditions import EqualCondition

class UserRegistrationFilter(InputFilter):
    # Field definitions
    username = field(
        required=True,
        filters=[StringTrimFilter()],
        validators=[IsStringValidator(), LengthValidator(min_length=3, max_length=20)]
    )

    email = field(
        required=True,
        validators=[IsStringValidator()]
    )

    password = field(required=True)
    password_confirmation = field(required=True)

    # Global filters applied to all fields
    global_filter(StringTrimFilter())

    # Global validators applied to all fields
    global_validator(IsStringValidator())

    # Conditions for cross-field validation
    condition(EqualCondition('password', 'password_confirmation'))

For detailed information about the declarative API, see:

Usage

Using the Validate Decorator

The most common way to use InputFilter is as a decorator on Flask routes:

from flask import Flask, g

app = Flask(__name__)

@app.route('/register', methods=['POST'])
@UserRegistrationFilter.validate()
def register():
    # Access validated data
    data = g.validated_data

    username = data['username']
    email = data['email']

    # Your registration logic here
    return {'message': 'User registered successfully'}

Manual Validation

You can also validate data manually:

filter_instance = UserRegistrationFilter()

filter_instance.set_data({
    'username': 'john_doe',
    'email': 'john@example.com',
    'password': 'secret123',
    'password_confirmation': 'secret123'
})

if not filter_instance.is_valid():
    print("Wrong credentials")
    return

print(f"Welcome {filter_instance.get_value('username')}!")

Model Serialization

InputFilter can automatically serialize validated data to model instances:

from dataclasses import dataclass
from flask_inputfilter.declarative import model

@dataclass
class User:
    username: str
    email: str

class UserFilter(InputFilter):
    username = field(required=True, validators=[IsStringValidator()])
    email = field(required=True, validators=[IsStringValidator()])

    # Associate with model
    model(User)

filter_instance = UserFilter()
filter_instance.set_data({
    'username': 'john_doe',
    'email': 'john@example.com'
})

if filter_instance.is_valid():
    # Access validated data and create model instance
    user_instance = User(
        username=filter_instance.get_value('username'),
        email=filter_instance.get_value('email')
    )

    # user_instance is now a User object
    assert isinstance(user_instance, User)
    assert user_instance.username == 'john_doe'

Key Methods

validate()

Class method that returns a decorator for Flask routes. Automatically validates request data and stores the result in g.validated_data.

@app.route('/api/users', methods=['POST'])
@UserFilter.validate()
def create_user():
    data = g.validated_data
    # Use validated data

set_data(data)

Instance method that sets the input data to be validated.

filter_instance = UserFilter()
filter_instance.set_data({'username': 'john'})

is_valid()

Instance method that validates the current data and returns True if valid, False otherwise.

if filter_instance.is_valid():
    # Data is valid, proceed with processing
    username = filter_instance.get_value('username')

get_value(field_name)

Instance method that returns the validated value for a specific field.

username = filter_instance.get_value('username')
email = filter_instance.get_value('email')

Error Handling

Flask-inputfilter provides error information when validation fails. You can access validation errors through the filter instance:

filter_instance = UserFilter()
filter_instance.set_data({'username': ''})  # Empty username

if not filter_instance.is_valid():
    errors = filter_instance.get_errors()
    # errors = {'username': 'This field is required'}

When using the decorator, validation errors automatically return a 400 response with the error details in JSON format.

Best Practices

  1. Organize Complex Filters: Break down complex filters into base classes using inheritance

  2. Model Integration: Use model serialization for type-safe data handling

  3. Global Components: Use global filters/validators for common processing (e.g., trimming strings)

class BaseFilter(InputFilter):
    # Common global filters and validators
    global_filter(StringTrimFilter())
    global_validator(IsStringValidator())

class UserFilter(BaseFilter):
    username = field(
        required=True,
        validators=[
            LengthValidator(
                min_length=3,
                max_length=20,
                message="Username must be between 3 and 20 characters"
            )
        ]
    )