# API Reference

## Schema

class `marshmallow.``Schema`(*, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Dict[KT, VT] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: str = None)

  Base schema class with which to define custom schemas.

  Example usage:

      import datetime as dt
      from dataclasses import dataclass

      from marshmallow import Schema, fields

      @dataclass
      class Album:
          title: str
          release_date: dt.date

      class AlbumSchema(Schema):
          title = fields.Str()
          release_date = fields.Date()

      album = Album("Beggars Banquet", dt.date(1968, 12, 6))
      schema = AlbumSchema()
      data = schema.dump(album)
      data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}

  Parameters:

  - only – Whitelist of the declared fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters.
  - exclude – Blacklist of the declared fields to exclude when instantiating the Schema. If a field appears in both `only` and `exclude`, it is not used. Nested fields can be represented with dot delimiters.
  - many – Should be set to `True` if `obj` is a collection so that the object will be serialized to a list.
  - context – Optional context passed to `fields.Method` and `fields.Function` fields.
  - load_only – Fields to skip during serialization (write-only fields)
  - dump_only – Fields to skip during deserialization (read-only fields)
  - partial – Whether to ignore missing fields and not require any fields declared. Propagates down to `Nested` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
  - unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.

  Changed in version 3.0.0: `prefix` parameter removed.

  Changed in version 2.0.0: `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of `marshmallow.decorators.validates_schema`, `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`. `__accessor__` and `__error_handler__` are deprecated. Implement the `handle_error` and `get_attribute` methods instead.

  class `Meta`

    Options object for a Schema.

    Example usage:

        class Meta:
            fields = ("id", "email", "date_created")
            exclude = ("password", "secret_attribute")

    Available options:

    - `fields`: Tuple or list of fields to include in the serialized result.
    - `additional`: Tuple or list of fields to include in addition to the
        explicitly declared fields. `additional` and `fields` are mutually-exclusive options.
    - `include`: Dictionary of additional fields to include in the schema. It is
        usually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an `OrderedDict`.
    - `exclude`: Tuple or list of fields to exclude in the serialized result.
        Nested fields can be represented with dot delimiters.
    - `dateformat`: Default format for `Date` fields.
    - `datetimeformat`: Default format for `DateTime` fields.
    - `render_module`: Module to use for `loads` and `dumps`.
        Defaults to `json` from the standard library.
    - `ordered`: If `True`, order serialization output according to the
        order in which fields were declared. Output of `Schema.dump` will be a `collections.OrderedDict`.
    - `index_errors`: If `True`, errors dictionaries will include the index
        of invalid items in a collection.
    - `load_only`: Tuple or list of fields to exclude from serialized results.
    - `dump_only`: Tuple or list of fields to exclude from deserialization
    - `unknown`: Whether to exclude, include, or raise an error for unknown
        fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
    - `register`: Whether to register the `Schema` with marshmallow’s internal
        class registry. Must be `True` if you intend to refer to this `Schema` by class name in `Nested` fields. Only set this to `False` when memory usage is critical. Defaults to `True`.
  `OPTIONS_CLASS`

    alias of `SchemaOpts`

  `dump`(obj: Any, *, many: bool = None)

    Serialize an object to native Python data types according to this Schema’s fields.

    Parameters:

    - obj – The object to serialize.
    - many – Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used.

    Returns: | A dict of serialized data
    Return type: | dict

    New in version 1.0.0.

    Changed in version 3.0.0b7: This method returns the serialized data rather than a `(data, errors)` duple. A `ValidationError` is raised if `obj` is invalid.

    Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

  `dumps`(obj: Any, *args, many: bool = None, **kwargs)

    Same as `dump()`, except return a JSON-encoded string.

    Parameters:

    - obj – The object to serialize.
    - many – Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used.

    Returns: | A `json` string
    Return type: | str

    New in version 1.0.0.

    Changed in version 3.0.0b7: This method returns the serialized data rather than a `(data, errors)` duple. A `ValidationError` is raised if `obj` is invalid.

  `error_messages` = {}

    Overrides for default schema-level error messages

  `fields` = None

    Dictionary mapping field_names -> `Field` objects

  classmethod `from_dict`(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema') → type

    Generate a `Schema` class given a dictionary of fields.

        from marshmallow import Schema, fields

        PersonSchema = Schema.from_dict({"name": fields.Str()})
        print(PersonSchema().load({"name": "David"}))  # => {'name': 'David'}

    Generated schemas are not added to the class registry and therefore cannot be referred to by name in `Nested` fields.

    Parameters:

    - fields (dict) – Dictionary mapping field names to field instances.
    - name (str) – Optional name for the class, which will appear in the `repr` for the class.

    New in version 3.0.0.

  `get_attribute`(obj: Any, attr: str, default: Any)

    Defines how to pull values from an object to serialize.

    New in version 2.0.0.

    Changed in version 3.0.0a1: Changed position of `obj` and `attr`.

  `handle_error`(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

    Custom error handler function for the schema.

    Parameters:

    - error – The `ValidationError` raised during (de)serialization.
    - data – The original input data.
    - many – Value of `many` on dump or load.
    - partial – Value of `partial` on load.

    New in version 2.0.0.

    Changed in version 3.0.0rc9: Receives `many` and `partial` (on deserialization) as keyword arguments.

  `load`(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: bool = None, partial: Union[bool, Sequence[str], Set[str]] = None, unknown: str = None)

    Deserialize a data structure to an object defined by this Schema’s fields.

    Parameters:

    - data – The data to deserialize.
    - many – Whether to deserialize `data` as a collection. If `None`, the value for `self.many` is used.
    - partial – Whether to ignore missing fields and not require any fields declared. Propagates down to `Nested` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
    - unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. If `None`, the value for `self.unknown` is used.

    Returns: | Deserialized data

    New in version 1.0.0.

    Changed in version 3.0.0b7: This method returns the deserialized data rather than a `(data, errors)` duple. A `ValidationError` is raised if invalid data are passed.

  `loads`(json_data: str, *, many: bool = None, partial: Union[bool, Sequence[str], Set[str]] = None, unknown: str = None, **kwargs)

    Same as `load()`, except it takes a JSON string as input.

    Parameters:

    - json_data – A JSON string of the data to deserialize.
    - many – Whether to deserialize `obj` as a collection. If `None`, the value for `self.many` is used.
    - partial – Whether to ignore missing fields and not require any fields declared. Propagates down to `Nested` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
    - unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. If `None`, the value for `self.unknown` is used.

    Returns: | Deserialized data

    New in version 1.0.0.

    Changed in version 3.0.0b7: This method returns the deserialized data rather than a `(data, errors)` duple. A `ValidationError` is raised if invalid data are passed.

  `on_bind_field`(field_name: str, field_obj: marshmallow.fields.Field) → None

    Hook to modify a field when it is bound to the `Schema`.

    No-op by default.

  `validate`(data: Mapping[KT, VT_co], *, many: bool = None, partial: Union[bool, Sequence[str], Set[str]] = None) → Dict[str, List[str]]

    Validate `data` against the schema, returning a dictionary of validation errors.

    Parameters:

    - data – The data to validate.
    - many – Whether to validate `data` as a collection. If `None`, the value for `self.many` is used.
    - partial – Whether to ignore missing fields and not require any fields declared. Propagates down to `Nested` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.

    Returns: | A dictionary of validation errors.

    New in version 1.1.0.

class `marshmallow.``SchemaOpts`(meta, ordered: bool = False)

  class Meta options for the `Schema`. Defines defaults.

## Fields

Field classes for various types of data.

class `marshmallow.fields.``Field`(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Sequence[Callable[[Any], Any]], Generator[Callable[[Any], Any], None, None]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)

  Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized or deserialized. On error, the name of the field will be returned.

  Parameters:

  - default – If set, this value will be used during serialization if the input value is missing. If not set, the field will be excluded from the serialized output if the input value is missing. May be a value or a callable.
  - missing – Default deserialization value for the field if the field is not found in the input data. May be a value or a callable.
  - data_key – The name of the dict key in the external representation, i.e. the input of `load` and the output of `dump`. If `None`, the key will match the name of the field.
  - attribute – The name of the attribute to get the value from when serializing. If `None`, assumes the attribute has the same name as the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use `data_key` instead.
  - validate – Validator or collection of validators that are called during deserialization. Validator takes a field’s input value as its only parameter and returns a boolean. If it returns `False`, an `ValidationError` is raised.
  - required – Raise a `ValidationError` if the field value is not supplied during deserialization.
  - allow_none – Set this to `True` if `None` should be considered a valid value during validation/deserialization. If `missing=None` and `allow_none` is unset, will default to `True`. Otherwise, the default is `False`.
  - load_only – If `True` skip this field during serialization, otherwise its value will be present in the serialized data.
  - dump_only – If `True` skip this field during deserialization, otherwise its value will be present in the deserialized object. In the context of an HTTP API, this effectively marks the field as “read-only”.
  - error_messages (dict) – Overrides for `Field.default_error_messages`.
  - metadata – Extra arguments to be stored as metadata.

  Changed in version 2.0.0: Removed `error` parameter. Use `error_messages` instead.

  Changed in version 2.0.0: Added `allow_none` parameter, which makes validation/deserialization of `None` consistent across fields.

  Changed in version 2.0.0: Added `load_only` and `dump_only` parameters, which allow field skipping during the (de)serialization process.

  Changed in version 2.0.0: Added `missing` parameter, which indicates the value for a field if the field is not found during deserialization.

  Changed in version 2.0.0: `default` value is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output.

  Changed in version 3.0.0b8: Add `data_key` parameter for the specifying the key in the input and output data. This parameter replaced both `load_from` and `dump_to`.

  `_bind_to_schema`(field_name, schema)

    Update field with values from its parent schema. Called by `Schema._bind_field`.

    Parameters:

    - field_name (str) – Field name set in schema.
    - schema (Schema) – Parent schema.

  `_deserialize`(value: Any, attr: Optional[str], data: Optional[Mapping[str, Any]], **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value: Any, attr: str, obj: Any, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

  `_validate`(value)

    Perform validation on `value`. Raise a `ValidationError` if validation does not succeed.

  `_validate_missing`(value)

    Validate missing values. Raise a `ValidationError` if `value` should be considered missing.

  `context`

    The context dictionary for the parent `Schema`.

  `default_error_messages` = {'null': 'Field may not be null.', 'required': 'Missing data for required field.', 'validator_failed': 'Invalid value.'}

    Default error messages for various kinds of errors. The keys in this dictionary are passed to `Field.make_error`. The values are error messages passed to `marshmallow.exceptions.ValidationError`.

  `deserialize`(value: Any, attr: str = None, data: Mapping[str, Any] = None, **kwargs)

    Deserialize `value`.

    Parameters:

    - value – The value to deserialize.
    - attr – The attribute/key in `data` to deserialize.
    - data – The raw input data passed to `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – If an invalid value is passed or if a required value is missing.

  `fail`(key: str, **kwargs)

    Helper method that raises a `ValidationError` with an error message from `self.error_messages`.

    Deprecated since version 3.0.0: Use `make_error` instead.

  `get_value`(obj, attr, accessor=None, default=<marshmallow.missing>)

    Return the value for a given key from an object.

    Parameters:

    - obj (object) – The object to get the value from.
    - attr (str) – The attribute/key in `obj` to get the value from.
    - accessor (callable) – A callable used to retrieve the value of `attr` from the object `obj`. Defaults to `marshmallow.utils.get_value`.

  `make_error`(key: str, **kwargs) → marshmallow.exceptions.ValidationError

    Helper method to make a `ValidationError` with an error message from `self.error_messages`.

  `root`

    Reference to the `Schema` that this field belongs to even if it is buried in a container field (e.g. `List`). Return `None` for unbound fields.

  `serialize`(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] = None, **kwargs)

    Pulls the value for the given key from the object, applies the field’s formatting and returns the result.

    Parameters:

    - attr – The attribute/key to get from the object.
    - obj – The object to access the attribute/key from.
    - accessor – Function used to access values from `obj`.
    - kwargs – Field-specific keyword arguments.

class `marshmallow.fields.``Raw`(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Sequence[Callable[[Any], Any]], Generator[Callable[[Any], Any], None, None]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)

  Field that applies no formatting.

class `marshmallow.fields.``Nested`(nested: Union[marshmallow.base.SchemaABC, type, str, Callable[[], marshmallow.base.SchemaABC]], *, default: Any = <marshmallow.missing>, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, unknown: str = None, **kwargs)

  Allows you to nest a `Schema` inside a field.

  Examples:

      class ChildSchema(Schema):
          id = fields.Str()
          name = fields.Str()
          # Use lambda functions when you need two-way nesting or self-nesting
          parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True)
          siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name"))))

      class ParentSchema(Schema):
          id = fields.Str()
          children = fields.List(
              fields.Nested(ChildSchema(only=("id", "parent", "siblings")))
          )
          spouse = fields.Nested(lambda: ParentSchema(only=("id",)))

  When passing a `Schema` instance as the first argument, the instance’s `exclude`, `only`, and `many` attributes will be respected.

  Therefore, when passing the `exclude`, `only`, or `many` arguments to `fields.Nested`, you should pass a `Schema` class (not an instance) as the first argument.

      # Yes
      author = fields.Nested(UserSchema, only=('id', 'name'))

      # No
      author = fields.Nested(UserSchema(), only=('id', 'name'))

  Parameters:

  - nested – The Schema class or class name (string) to nest, or `"self"` to nest the `Schema` within itself.
  - exclude – A list or tuple of fields to exclude.
  - only – A list or tuple of fields to marshal. If `None`, all fields are marshalled. This parameter takes precedence over `exclude`.
  - many – Whether the field is a collection of objects.
  - unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
  - kwargs – The same keyword arguments that `Field` receives.

  `_deserialize`(value, attr, data, partial=None, many=False, **kwargs)

    Same as `Field._deserialize()` with additional `partial` argument.

    Parameters: | partial (bool|tuple) – For nested schemas, the `partial` parameter passed to `Schema.load`.

    Changed in version 3.0.0: Add `partial` parameter.

  `_serialize`(nested_obj, attr, obj, many=False, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

  `schema`

    The nested Schema object.

    Changed in version 1.0.0: Renamed from `serializer` to `schema`.

class `marshmallow.fields.``Mapping`(keys: Union[marshmallow.fields.Field, type] = None, values: Union[marshmallow.fields.Field, type] = None, **kwargs)

  An abstract class for objects with key-value pairs.

  Parameters:

  - keys – A field class or instance for dict keys.
  - values – A field class or instance for dict values.
  - kwargs – The same keyword arguments that `Field` receives.

  Note

  When the structure of nested data is not known, you may omit the `keys` and `values` arguments to prevent content validation.

  New in version 3.0.0rc4.

  `_bind_to_schema`(field_name, schema)

    Update field with values from its parent schema. Called by `Schema._bind_field`.

    Parameters:

    - field_name (str) – Field name set in schema.
    - schema (Schema) – Parent schema.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

  `mapping_type`

    alias of `builtins.dict`

class `marshmallow.fields.``Dict`(keys: Union[marshmallow.fields.Field, type] = None, values: Union[marshmallow.fields.Field, type] = None, **kwargs)

  A dict field. Supports dicts and dict-like objects. Extends Mapping with dict as the mapping_type.

  Example:

      numbers = fields.Dict(keys=fields.Str(), values=fields.Float())

  Parameters: | kwargs – The same keyword arguments that `Mapping` receives.

  New in version 2.1.0.

  `mapping_type`

    alias of `builtins.dict`

class `marshmallow.fields.``List`(cls_or_instance: Union[marshmallow.fields.Field, type], **kwargs)

  A list field, composed with another `Field` class or instance.

  Example:

      numbers = fields.List(fields.Float())

  Parameters:

  - cls_or_instance – A field class or instance.
  - kwargs – The same keyword arguments that `Field` receives.

  Changed in version 2.0.0: The `allow_none` parameter now applies to deserialization and has the same semantics as the other fields.

  Changed in version 3.0.0rc9: Does not serialize scalar values to single-item lists.

  `_bind_to_schema`(field_name, schema)

    Update field with values from its parent schema. Called by `Schema._bind_field`.

    Parameters:

    - field_name (str) – Field name set in schema.
    - schema (Schema) – Parent schema.

  `_deserialize`(value, attr, data, **kwargs) → List[Any]

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs) → Optional[List[Any]]

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``Tuple`(tuple_fields, *args, **kwargs)

  A tuple field, composed of a fixed number of other `Field` classes or instances

  Example:

      row = Tuple((fields.String(), fields.Integer(), fields.Float()))

  Note

  Because of the structured nature of `collections.namedtuple` and `typing.NamedTuple`, using a Schema within a Nested field for them is more appropriate than using a `Tuple` field.

  Parameters:

  - tuple_fields (Iterable[Field]) – An iterable of field classes or instances.
  - kwargs – The same keyword arguments that `Field` receives.

  New in version 3.0.0rc4.

  `_bind_to_schema`(field_name, schema)

    Update field with values from its parent schema. Called by `Schema._bind_field`.

    Parameters:

    - field_name (str) – Field name set in schema.
    - schema (Schema) – Parent schema.

  `_deserialize`(value, attr, data, **kwargs) → Tuple

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs) → Optional[Tuple]

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``String`(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Sequence[Callable[[Any], Any]], Generator[Callable[[Any], Any], None, None]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)

  A string field.

  Parameters: | kwargs – The same keyword arguments that `Field` receives.

  `_deserialize`(value, attr, data, **kwargs) → Any

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs) → Optional[str]

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``UUID`(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Sequence[Callable[[Any], Any]], Generator[Callable[[Any], Any], None, None]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)

  A UUID field.

  `_deserialize`(value, attr, data, **kwargs) → Optional[uuid.UUID]

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_validated`(value) → Optional[uuid.UUID]

    Format the value or raise a `ValidationError` if an error occurs.

class `marshmallow.fields.``Number`(*, as_string: bool = False, **kwargs)

  Base class for number fields.

  Parameters:

  - as_string (bool) – If `True`, format the serialized value as a string.
  - kwargs – The same keyword arguments that `Field` receives.

  `_deserialize`(value, attr, data, **kwargs) → Optional[_T]

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_format_num`(value) → Any

    Return the number value for value, given this field’s `num_type`.

  `_serialize`(value, attr, obj, **kwargs) → Union[str, _T, None]

    Return a string if `self.as_string=True`, otherwise return this field’s `num_type`.

  `_validated`(value) → Optional[_T]

    Format the value or raise a `ValidationError` if an error occurs.

  `num_type`

    alias of `builtins.float`

class `marshmallow.fields.``Integer`(*, strict: bool = False, **kwargs)

  An integer field.

  Parameters:

  - strict – If `True`, only integer types are valid. Otherwise, any value castable to `int` is valid.
  - kwargs – The same keyword arguments that `Number` receives.

  `_validated`(value)

    Format the value or raise a `ValidationError` if an error occurs.

  `num_type`

    alias of `builtins.int`

class `marshmallow.fields.``Decimal`(places: int = None, rounding: str = None, *, allow_nan: bool = False, as_string: bool = False, **kwargs)

  A field that (de)serializes to the Python `decimal.Decimal` type. It’s safe to use when dealing with money values, percentages, ratios or other numbers where precision is critical.

  Warning

  This field serializes to a `decimal.Decimal` object by default. If you need to render your data as JSON, keep in mind that the `json` module from the standard library does not encode `decimal.Decimal`. Therefore, you must use a JSON library that can handle decimals, such as `simplejson`, or serialize to a string by passing `as_string=True`.

  Warning

  If a JSON `float` value is passed to this field for deserialization it will first be cast to its corresponding `string` value before being deserialized to a `decimal.Decimal` object. The default `__str__` implementation of the built-in Python `float` type may apply a destructive transformation upon its input data and therefore cannot be relied upon to preserve precision. To avoid this, you can instead pass a JSON `string` to be deserialized directly.

  Parameters:

  - places – How many decimal places to quantize the value. If `None`, does not quantize the value.
  - rounding – How to round the value during quantize, for example `decimal.ROUND_UP`. If `None`, uses the rounding value from the current thread’s context.
  - allow_nan – If `True`, `NaN`, `Infinity` and `-Infinity` are allowed, even though they are illegal according to the JSON specification.
  - as_string – If `True`, serialize to a string instead of a Python `decimal.Decimal` type.
  - kwargs – The same keyword arguments that `Number` receives.

  New in version 1.2.0.

  `_format_num`(value)

    Return the number value for value, given this field’s `num_type`.

  `_validated`(value)

    Format the value or raise a `ValidationError` if an error occurs.

  `num_type`

    alias of `decimal.Decimal`

class `marshmallow.fields.``Boolean`(*, truthy: Set[T] = None, falsy: Set[T] = None, **kwargs)

  A boolean field.

  Parameters:

  - truthy – Values that will (de)serialize to `True`. If an empty set, any non-falsy value will deserialize to `True`. If `None`, `marshmallow.fields.Boolean.truthy` will be used.
  - falsy – Values that will (de)serialize to `False`. If `None`, `marshmallow.fields.Boolean.falsy` will be used.
  - kwargs – The same keyword arguments that `Field` receives.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

  `falsy` = {0, 'no', 'No', 'n', 'N', '0', 'false', 'FALSE', 'f', 'Off', 'F', 'False', 'NO', 'off', 'OFF'}

    Default falsy values.

  `truthy` = {'on', 't', 'ON', 'true', 1, 'T', 'yes', 'On', 'Y', '1', 'True', 'y', 'TRUE', 'Yes', 'YES'}

    Default truthy values.

class `marshmallow.fields.``Float`(*, allow_nan: bool = False, as_string: bool = False, **kwargs)

  A double as an IEEE-754 double precision string.

  Parameters:

  - allow_nan (bool) – If `True`, `NaN`, `Infinity` and `-Infinity` are allowed, even though they are illegal according to the JSON specification.
  - as_string (bool) – If `True`, format the value as a string.
  - kwargs – The same keyword arguments that `Number` receives.

  `_validated`(value)

    Format the value or raise a `ValidationError` if an error occurs.

  `num_type`

    alias of `builtins.float`

class `marshmallow.fields.``DateTime`(format: str = None, **kwargs)

  A formatted datetime string.

  Example: `'2014-12-22T03:12:58.019077+00:00'`

  Parameters:

  - format – Either `"rfc"` (for RFC822), `"iso"` (for ISO8601), or a date format string. If `None`, defaults to “iso”.
  - kwargs – The same keyword arguments that `Field` receives.

  Changed in version 3.0.0rc9: Does not modify timezone information on (de)serialization.

  `_bind_to_schema`(field_name, schema)

    Update field with values from its parent schema. Called by `Schema._bind_field`.

    Parameters:

    - field_name (str) – Field name set in schema.
    - schema (Schema) – Parent schema.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``NaiveDateTime`(format: str = None, *, timezone: datetime.timezone = None, **kwargs)

  A formatted naive datetime string.

  Parameters:

  - format – See `DateTime`.
  - timezone – Used on deserialization. If `None`, aware datetimes are rejected. If not `None`, aware datetimes are converted to this timezone before their timezone information is removed.
  - kwargs – The same keyword arguments that `Field` receives.

  New in version 3.0.0rc9.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

class `marshmallow.fields.``AwareDateTime`(format: str = None, *, default_timezone: datetime.timezone = None, **kwargs)

  A formatted aware datetime string.

  Parameters:

  - format – See `DateTime`.
  - default_timezone – Used on deserialization. If `None`, naive datetimes are rejected. If not `None`, naive datetimes are set this timezone.
  - kwargs – The same keyword arguments that `Field` receives.

  New in version 3.0.0rc9.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

class `marshmallow.fields.``Time`(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Sequence[Callable[[Any], Any]], Generator[Callable[[Any], Any], None, None]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)

  ISO8601-formatted time string.

  Parameters: | kwargs – The same keyword arguments that `Field` receives.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize an ISO8601-formatted time to a `datetime.time` object.

  `_serialize`(value, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``Date`(format: str = None, **kwargs)

  ISO8601-formatted date string.

  Parameters:

  - format – Either `"iso"` (for ISO8601) or a date format string. If `None`, defaults to “iso”.
  - kwargs – The same keyword arguments that `Field` receives.

class `marshmallow.fields.``TimeDelta`(precision: str = 'seconds', **kwargs)

  A field that (de)serializes a `datetime.timedelta` object to an integer and vice versa. The integer can represent the number of days, seconds or microseconds.

  Parameters:

  - precision – Influences how the integer is interpreted during (de)serialization. Must be ‘days’, ‘seconds’, ‘microseconds’, ‘milliseconds’, ‘minutes’, ‘hours’ or ‘weeks’.
  - kwargs – The same keyword arguments that `Field` receives.

  Changed in version 2.0.0: Always serializes to an integer value to avoid rounding errors. Add `precision` parameter.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``Url`(*, relative: bool = False, schemes: Union[Sequence[str], Set[str]] = None, require_tld: bool = True, **kwargs)

  A validated URL field. Validation occurs during both serialization and deserialization.

  Parameters:

  - default – Default value for the field if the attribute is not set.
  - relative – Whether to allow relative URLs.
  - require_tld – Whether to reject non-FQDN hostnames.
  - schemes – Valid schemes. By default, `http`, `https`, `ftp`, and `ftps` are allowed.
  - kwargs – The same keyword arguments that `String` receives.

`marshmallow.fields.``URL`

  alias of `marshmallow.fields.Url`

class `marshmallow.fields.``Email`(*args, **kwargs)

  A validated email field. Validation occurs during both serialization and deserialization.

  Parameters:

  - args – The same positional arguments that `String` receives.
  - kwargs – The same keyword arguments that `String` receives.

class `marshmallow.fields.``Method`(serialize: str = None, deserialize: str = None, **kwargs)

  A field that takes the value returned by a `Schema` method.

  Parameters:

  - serialize (str) – The name of the Schema method from which to retrieve the value. The method must take an argument `obj` (in addition to self) that is the object to be serialized.
  - deserialize (str) – Optional name of the Schema method for deserializing a value The method must take a single argument `value`, which is the value to deserialize.

  Changed in version 2.0.0: Removed optional `context` parameter on methods. Use `self.context` instead.

  Changed in version 2.3.0: Deprecated `method_name` parameter in favor of `serialize` and allow `serialize` to not be passed at all.

  Changed in version 3.0.0: Removed `method_name` parameter.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``Function`(serialize: Union[Callable[[Any], Any], Callable[[Any, Dict[KT, VT]], Any]] = None, deserialize: Union[Callable[[Any], Any], Callable[[Any, Dict[KT, VT]], Any]] = None, **kwargs)

  A field that takes the value returned by a function.

  Parameters:

  - serialize – A callable from which to retrieve the value. The function must take a single argument `obj` which is the object to be serialized. It can also optionally take a `context` argument, which is a dictionary of context variables passed to the serializer. If no callable is provided then the ``load_only`` flag will be set to True.
  - deserialize – A callable from which to retrieve the value. The function must take a single argument `value` which is the value to be deserialized. It can also optionally take a `context` argument, which is a dictionary of context variables passed to the deserializer. If no callable is provided then ``value`` will be passed through unchanged.

  Changed in version 2.3.0: Deprecated `func` parameter in favor of `serialize`.

  Changed in version 3.0.0a1: Removed `func` parameter.

  `_deserialize`(value, attr, data, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

`marshmallow.fields.``Str`

  alias of `marshmallow.fields.String`

`marshmallow.fields.``Bool`

  alias of `marshmallow.fields.Boolean`

`marshmallow.fields.``Int`

  alias of `marshmallow.fields.Integer`

class `marshmallow.fields.``Constant`(constant: Any, **kwargs)

  A field that (de)serializes to a preset constant. If you only want the constant added for serialization or deserialization, you should use `dump_only=True` or `load_only=True` respectively.

  Parameters: | constant – The constant to return for the field attribute.

  New in version 2.0.0.

  `_deserialize`(value, *args, **kwargs)

    Deserialize value. Concrete `Field` classes should implement this method.

    Parameters:

    - value – The value to be deserialized.
    - attr – The attribute/key in `data` to be deserialized.
    - data – The raw input data passed to the `Schema.load`.
    - kwargs – Field-specific keyword arguments.

    Raises: | ValidationError – In case of formatting or validation failure.
    Returns: | The deserialized value.

    Changed in version 2.0.0: Added `attr` and `data` parameters.

    Changed in version 3.0.0: Added `**kwargs` to signature.

  `_serialize`(value, *args, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

class `marshmallow.fields.``Pluck`(nested: Union[marshmallow.base.SchemaABC, type, str, Callable[[], marshmallow.base.SchemaABC]], field_name: str, **kwargs)

  Allows you to replace nested data with one of the data’s fields.

  Example:

      from marshmallow import Schema, fields

      class ArtistSchema(Schema):
          id = fields.Int()
          name = fields.Str()

      class AlbumSchema(Schema):
          artist = fields.Pluck(ArtistSchema, 'id')

      in_data = {'artist': 42}
      loaded = AlbumSchema().load(in_data) # => {'artist': {'id': 42}}
      dumped = AlbumSchema().dump(loaded)  # => {'artist': 42}

  Parameters:

  - nested (Schema) – The Schema class or class name (string) to nest, or `"self"` to nest the `Schema` within itself.
  - field_name (str) – The key to pluck a value from.
  - kwargs – The same keyword arguments that `Nested` receives.

  `_deserialize`(value, attr, data, partial=None, **kwargs)

    Same as `Field._deserialize()` with additional `partial` argument.

    Parameters: | partial (bool|tuple) – For nested schemas, the `partial` parameter passed to `Schema.load`.

    Changed in version 3.0.0: Add `partial` parameter.

  `_serialize`(nested_obj, attr, obj, **kwargs)

    Serializes `value` to a basic Python datatype. Noop by default. Concrete `Field` classes should implement this method.

    Example:

        class TitleCase(Field):
            def _serialize(self, value, attr, obj, **kwargs):
                if not value:
                    return ''
                return str(value).title()

    Parameters:

    - value – The value to be serialized.
    - attr (str) – The attribute or key on the object to be serialized.
    - obj (object) – The object the value was pulled from.
    - kwargs (dict) – Field-specific keyword arguments.

    Returns: | The serialized value

## Decorators

Decorators for registering schema pre-processing and post-processing methods. These should be imported from the top-level `marshmallow` module.

Methods decorated with `pre_load`, `post_load`, `pre_dump`, `post_dump`, and `validates_schema` receive `many` as a keyword argument. In addition, `pre_load`, `post_load`, and `validates_schema` receive `partial`. If you don’t need these arguments, add `**kwargs` to your method signature.

Example:

    from marshmallow import (
        Schema, pre_load, pre_dump, post_load, validates_schema,
        validates, fields, ValidationError
    )

    class UserSchema(Schema):

        email = fields.Str(required=True)
        age = fields.Integer(required=True)

        @post_load
        def lowerstrip_email(self, item, many, **kwargs):
            item['email'] = item['email'].lower().strip()
            return item

        @pre_load(pass_many=True)
        def remove_envelope(self, data, many, **kwargs):
            namespace = 'results' if many else 'result'
            return data[namespace]

        @post_dump(pass_many=True)
        def add_envelope(self, data, many, **kwargs):
            namespace = 'results' if many else 'result'
            return {namespace: data}

        @validates_schema
        def validate_email(self, data, **kwargs):
            if len(data['email']) < 3:
                raise ValidationError('Email must be more than 3 characters', 'email')

        @validates('age')
        def validate_age(self, data, **kwargs):
            if data < 14:
                raise ValidationError('Too young!')

Note

These decorators only work with instance methods. Class and static methods are not supported.

Warning

The invocation order of decorated methods of the same type is not guaranteed. If you need to guarantee order of different processing steps, you should put them in the same processing method.

`marshmallow.decorators.``post_dump`(fn=None, pass_many=False, pass_original=False)

  Register a method to invoke after serializing an object. The method receives the serialized object and returns the processed object.

  By default it receives a single object at a time, transparently handling the `many` argument passed to the `Schema`’s `dump()` call. If `pass_many=True`, the raw data (which may be a collection) is passed.

  If `pass_original=True`, the original data (before serializing) will be passed as an additional argument to the method.

  Changed in version 3.0.0: `many` is always passed as a keyword arguments to the decorated method.

`marshmallow.decorators.``post_load`(fn=None, pass_many=False, pass_original=False)

  Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data.

  By default it receives a single object at a time, transparently handling the `many` argument passed to the `Schema`’s `load()` call. If `pass_many=True`, the raw data (which may be a collection) is passed.

  If `pass_original=True`, the original data (before deserializing) will be passed as an additional argument to the method.

  Changed in version 3.0.0: `partial` and `many` are always passed as keyword arguments to the decorated method.

`marshmallow.decorators.``pre_dump`(fn=None, pass_many=False)

  Register a method to invoke before serializing an object. The method receives the object to be serialized and returns the processed object.

  By default it receives a single object at a time, transparently handling the `many` argument passed to the `Schema`’s `dump()` call. If `pass_many=True`, the raw data (which may be a collection) is passed.

  Changed in version 3.0.0: `many` is always passed as a keyword arguments to the decorated method.

`marshmallow.decorators.``pre_load`(fn=None, pass_many=False)

  Register a method to invoke before deserializing an object. The method receives the data to be deserialized and returns the processed data.

  By default it receives a single object at a time, transparently handling the `many` argument passed to the `Schema`’s `load()` call. If `pass_many=True`, the raw data (which may be a collection) is passed.

  Changed in version 3.0.0: `partial` and `many` are always passed as keyword arguments to the decorated method.

`marshmallow.decorators.``set_hook`(fn, key, **kwargs)

  Mark decorated function as a hook to be picked up later. You should not need to use this method directly.

  Note

  Currently only works with functions and instance methods. Class and static methods are not supported.

  Returns: | Decorated function if supplied, else this decorator with its args bound.

`marshmallow.decorators.``validates`(field_name: str)

  Register a field validator.

  Parameters: | field_name (str) – Name of the field that the method validates.

`marshmallow.decorators.``validates_schema`(fn=None, pass_many=False, pass_original=False, skip_on_field_errors=True)

  Register a schema-level validator.

  By default it receives a single object at a time, transparently handling the `many` argument passed to the `Schema`’s `validate()` call. If `pass_many=True`, the raw data (which may be a collection) is passed.

  If `pass_original=True`, the original data (before unmarshalling) will be passed as an additional argument to the method.

  If `skip_on_field_errors=True`, this validation method will be skipped whenever validation errors have been detected when validating fields.

  Changed in version 3.0.0b1: `skip_on_field_errors` defaults to `True`.

  Changed in version 3.0.0: `partial` and `many` are always passed as keyword arguments to the decorated method.

## Validators

Validation classes for various types of data.

class `marshmallow.validate.``ContainsOnly`(choices: Iterable[T_co], labels: Iterable[str] = None, *, error: str = None)

  Validator which succeeds if `value` is a sequence and each element in the sequence is also in the sequence passed as `choices`. Empty input is considered valid.

  Parameters:

  - choices (iterable) – Same as `OneOf`.
  - labels (iterable) – Same as `OneOf`.
  - error (str) – Same as `OneOf`.

  Changed in version 3.0.0b2: Duplicate values are considered valid.

  Changed in version 3.0.0b2: Empty input is considered valid. Use `validate.Length(min=1)` to validate against empty inputs.

class `marshmallow.validate.``Email`(*, error: str = None)

  Validate an email address.

  Parameters: | error – Error message to raise in case of a validation error. Can be interpolated with `{input}`.

class `marshmallow.validate.``Equal`(comparable, *, error: str = None)

  Validator which succeeds if the `value` passed to it is equal to `comparable`.

  Parameters:

  - comparable – The object to compare to.
  - error – Error message to raise in case of a validation error. Can be interpolated with `{input}` and `{other}`.

class `marshmallow.validate.``Length`(min: int = None, max: int = None, *, equal: int = None, error: str = None)

  Validator which succeeds if the value passed to it has a length between a minimum and maximum. Uses len(), so it can work for strings, lists, or anything with length.

  Parameters:

  - min – The minimum length. If not provided, minimum length will not be checked.
  - max – The maximum length. If not provided, maximum length will not be checked.
  - equal – The exact length. If provided, maximum and minimum length will not be checked.
  - error – Error message to raise in case of a validation error. Can be interpolated with `{input}`, `{min}` and `{max}`.

class `marshmallow.validate.``NoneOf`(iterable: Iterable[T_co], *, error: str = None)

  Validator which fails if `value` is a member of `iterable`.

  Parameters:

  - iterable – A sequence of invalid values.
  - error – Error message to raise in case of a validation error. Can be interpolated using `{input}` and `{values}`.

class `marshmallow.validate.``OneOf`(choices: Iterable[T_co], labels: Iterable[str] = None, *, error: str = None)

  Validator which succeeds if `value` is a member of `choices`.

  Parameters:

  - choices – A sequence of valid values.
  - labels – Optional sequence of labels to pair with the choices.
  - error – Error message to raise in case of a validation error. Can be interpolated with `{input}`, `{choices}` and `{labels}`.

  `options`(valuegetter: Union[str, Callable[[Any], Any]] = <class 'str'>) → Iterable[Tuple[Any, str]]

    Return a generator over the (value, label) pairs, where value is a string associated with each choice. This convenience method is useful to populate, for instance, a form select field.

    Parameters: | valuegetter – Can be a callable or a string. In the former case, it must be a one-argument callable which returns the value of a choice. In the latter case, the string specifies the name of an attribute of the choice objects. Defaults to `str()` or `str()`.

class `marshmallow.validate.``Predicate`(method: str, *, error: str = None, **kwargs)

  Call the specified `method` of the `value` object. The validator succeeds if the invoked method returns an object that evaluates to True in a Boolean context. Any additional keyword argument will be passed to the method.

  Parameters:

  - method – The name of the method to invoke.
  - error – Error message to raise in case of a validation error. Can be interpolated with `{input}` and `{method}`.
  - kwargs – Additional keyword arguments to pass to the method.

class `marshmallow.validate.``Range`(min=None, max=None, *, min_inclusive: bool = True, max_inclusive: bool = True, error: str = None)

  Validator which succeeds if the value passed to it is within the specified range. If `min` is not specified, or is specified as `None`, no lower bound exists. If `max` is not specified, or is specified as `None`, no upper bound exists. The inclusivity of the bounds (if they exist) is configurable. If `min_inclusive` is not specified, or is specified as `True`, then the `min` bound is included in the range. If `max_inclusive` is not specified, or is specified as `True`, then the `max` bound is included in the range.

  Parameters:

  - min – The minimum value (lower bound). If not provided, minimum value will not be checked.
  - max – The maximum value (upper bound). If not provided, maximum value will not be checked.
  - min_inclusive – Whether the `min` bound is included in the range.
  - max_inclusive – Whether the `max` bound is included in the range.
  - error – Error message to raise in case of a validation error. Can be interpolated with `{input}`, `{min}` and `{max}`.

class `marshmallow.validate.``Regexp`(regex: Union[str, bytes, Pattern[AnyStr]], flags=0, *, error: str = None)

  Validator which succeeds if the `value` matches `regex`.

  Note

  Uses `re.match`, which searches for a match at the beginning of a string.

  Parameters:

  - regex – The regular expression string to use. Can also be a compiled regular expression pattern.
  - flags – The regexp flags to use, for example re.IGNORECASE. Ignored if `regex` is not a string.
  - error – Error message to raise in case of a validation error. Can be interpolated with `{input}` and `{regex}`.

class `marshmallow.validate.``URL`(*, relative: bool = False, schemes: Union[Sequence[str], Set[str]] = None, require_tld: bool = True, error: str = None)

  Validate a URL.

  Parameters:

  - relative – Whether to allow relative URLs.
  - error – Error message to raise in case of a validation error. Can be interpolated with `{input}`.
  - schemes – Valid schemes. By default, `http`, `https`, `ftp`, and `ftps` are allowed.
  - require_tld – Whether to reject non-FQDN hostnames.

class `marshmallow.validate.``Validator`

  Base abstract class for validators.

  Note

  This class does not provide any behavior. It is only used to add a useful `__repr__` implementation for validators.

## Utility Functions

Utility methods for marshmallow.

`marshmallow.utils.``callable_or_raise`(obj)

  Check that an object is callable, else raise a `ValueError`.

`marshmallow.utils.``from_iso_date`(value)

  Parse a string and return a datetime.date.

`marshmallow.utils.``from_iso_datetime`(value)

  Parse a string and return a datetime.datetime.

  This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC.

`marshmallow.utils.``from_iso_time`(value)

  Parse a string and return a datetime.time.

  This function doesn’t support time zone offsets.

`marshmallow.utils.``from_rfc`(datestring: str) → datetime.datetime

  Parse a RFC822-formatted datetime string and return a datetime object.

  https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime # noqa: B950

`marshmallow.utils.``get_fixed_timezone`(offset: Union[int, float, datetime.timedelta]) → datetime.timezone

  Return a tzinfo instance with a fixed offset from UTC.

`marshmallow.utils.``get_func_args`(func: Callable) → List[str]

  Given a callable, return a list of argument names. Handles `functools.partial` objects and class-based callables.

  Changed in version 3.0.0a1: Do not return bound arguments, eg. `self`.

`marshmallow.utils.``get_value`(obj, key: Union[int, str], default=<marshmallow.missing>)

  Helper for pulling a keyed value off various types of objects. Fields use this method by default to access attributes of the source object. For object `x` and attribute `i`, this method first tries to access `x[i]`, and then falls back to `x.i` if an exception is raised.

  Warning

  If an object `x` does not raise an exception when `x[i]` does not exist, `get_value` will never check the value `x.i`. Consider overriding `marshmallow.fields.Field.get_value` in this case.

`marshmallow.utils.``is_collection`(obj) → bool

  Return True if `obj` is a collection type, e.g list, tuple, queryset.

`marshmallow.utils.``is_generator`(obj) → bool

  Return True if `obj` is a generator

`marshmallow.utils.``is_instance_or_subclass`(val, class_) → bool

  Return True if `val` is either a subclass or instance of `class_`.

`marshmallow.utils.``is_iterable_but_not_string`(obj) → bool

  Return True if `obj` is an iterable object that isn’t a string.

`marshmallow.utils.``is_keyed_tuple`(obj) → bool

  Return True if `obj` has keyed tuple behavior, such as namedtuples or SQLAlchemy’s KeyedTuples.

`marshmallow.utils.``isoformat`(datetime: datetime.datetime) → str

  Return the ISO8601-formatted representation of a datetime object.

  Parameters: | datetime (datetime) – The datetime.

`marshmallow.utils.``pluck`(dictlist: List[Dict[str, Any]], key: str)

  Extracts a list of dictionary values from a list of dictionaries.

      >>> dlist = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}]
      >>> pluck(dlist, 'id')
      [1, 2]

`marshmallow.utils.``pprint`(obj, *args, **kwargs) → None

  Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. Useful for printing the output of `marshmallow.Schema.dump()`.

`marshmallow.utils.``resolve_field_instance`(cls_or_instance)

  Return a Schema instance from a Schema class or instance.

  Parameters: | cls_or_instance (type|Schema) – Marshmallow Schema class or instance.

`marshmallow.utils.``rfcformat`(datetime: datetime.datetime) → str

  Return the RFC822-formatted representation of a datetime object.

  Parameters: | datetime (datetime) – The datetime.

`marshmallow.utils.``set_value`(dct: Dict[str, Any], key: str, value: Any)

  Set a value in a dict. If `key` contains a ‘.’, it is assumed be a path (i.e. dot-delimited string) to the value’s location.

      >>> d = {}
      >>> set_value(d, 'foo.bar', 42)
      >>> d
      {'foo': {'bar': 42}}

## Error Store

Utilities for storing collections of error messages.

Warning

This module is treated as private API. Users should not need to use this module directly.

`marshmallow.error_store.``merge_errors`(errors1, errors2)

  Deeply merge two error messages.

  The format of `errors1` and `errors2` matches the `message` parameter of `marshmallow.exceptions.ValidationError`.

## Class Registry

A registry of `Schema` classes. This allows for string lookup of schemas, which may be used with class:`fields.Nested`.

Warning

This module is treated as private API. Users should not need to use this module directly.

`marshmallow.class_registry.``get_class`(classname: str, all: bool = False) → Union[List[Schema], Schema]

  Retrieve a class from the registry.

  Raises: | marshmallow.exceptions.RegistryError if the class cannot be found or if there are multiple entries for the given class name.

`marshmallow.class_registry.``register`(classname: str, cls: Schema) → None

  Add a class to the registry of serializer classes. When a class is registered, an entry for both its classname and its full, module-qualified path are added to the registry.

  Example:

      class MyClass:
          pass

      register('MyClass', MyClass)
      # Registry:
      # {
      #   'MyClass': [path.to.MyClass],
      #   'path.to.MyClass': [path.to.MyClass],
      # }

## Exceptions

Exception classes for marshmallow-related errors.

exception `marshmallow.exceptions.``FieldInstanceResolutionError`

  Raised when schema to instantiate is neither a Schema class nor an instance.

exception `marshmallow.exceptions.``MarshmallowError`

  Base class for all marshmallow-related errors.

exception `marshmallow.exceptions.``RegistryError`

  Raised when an invalid operation is performed on the serializer class registry.

exception `marshmallow.exceptions.``StringNotCollectionError`

  Raised when a string is passed when a list of strings is expected.

exception `marshmallow.exceptions.``ValidationError`(message: Union[str, List[T], Dict[KT, VT]], field_name: str = '_schema', data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]] = None, valid_data: Union[List[Dict[str, Any]], Dict[str, Any]] = None, **kwargs)

  Raised when validation fails on a field or schema.

  Validators and custom fields should raise this exception.

  Parameters:

  - message – An error message, list of error messages, or dict of error messages. If a dict, the keys are subitems and the values are error messages.
  - field_name – Field name to store the error on. If `None`, the error is stored as schema-level error.
  - data – Raw input data.
  - valid_data – Valid (de)serialized data.