Fields

Base Field Class

class marshmallow.fields.Field(*, load_default=<marshmallow.missing>, missing=<marshmallow.missing>, dump_default=<marshmallow.missing>, default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None, **additional_metadata)[source]

Base field from which other fields inherit.

Parameters:
  • dump_default (Any) – 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.

  • load_default (Any) – 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 (str | None) – 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 (str | None) – The name of the key/attribute in the internal representation, i.e. the output of load and the input of dump. If None, the key/attribute will match the name of the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute, or using keys/attributes that are invalid variable names, unsuitable for field names. In most cases, you should use data_key instead.

  • validate (types.Validator | Iterable[types.Validator] | None) – 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 (bool) – Raise a ValidationError if the field value is not supplied during deserialization.

  • allow_none (bool | None) – Set this to True if None should be considered a valid value during validation/deserialization. If set to False (the default), None is considered invalid input. If load_default is explicitly set to None and allow_none is unset, allow_none is implicitly set to True.

  • load_only (bool) – If True skip this field during serialization, otherwise its value will be present in the serialized data.

  • dump_only (bool) – 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[str, str] | None) – Overrides for Field.default_error_messages.

  • metadata (Mapping[str, Any] | None) – Extra information to be stored as field metadata.

  • missing (Any)

  • default (Any)

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.

Changed in version 3.13.0: Replace missing and default parameters with load_default and dump_default.

Changed in version 3.24.0: Field should no longer be used as a field within a Schema. Use Raw or another Field subclass instead.

Field subclasses

Classes:

AwareDateTime

A formatted aware datetime string.

Bool

alias of Boolean

Boolean

A boolean field.

Constant

A field that (de)serializes to a preset constant.

Date

ISO8601-formatted date string.

DateTime

A formatted datetime string.

Decimal

A field that (de)serializes to the Python decimal.Decimal type.

Dict

A dict field.

Email

An email field.

Enum

An Enum field (de)serializing enum members by symbol (name) or by value.

Float

A double as an IEEE-754 double precision string.

Function

A field that takes the value returned by a function.

IP

A IP address field.

IPInterface

A IPInterface field.

IPv4

A IPv4 address field.

IPv4Interface

A IPv4 Network Interface field.

IPv6

A IPv6 address field.

IPv6Interface

A IPv6 Network Interface field.

Int

alias of Integer

Integer

An integer field.

List

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

Mapping

An abstract class for objects with key-value pairs.

Method

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

NaiveDateTime

A formatted naive datetime string.

Nested

Allows you to nest a Schema inside a field.

Number

Base class for number fields.

Pluck

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

Raw

Field that applies no formatting.

Str

alias of String

String

A string field.

Time

A formatted time string.

TimeDelta

A field that (de)serializes a datetime.timedelta object to an integer or float and vice versa.

Tuple

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

URL

alias of Url

UUID

A UUID field.

Url

An URL field.

class marshmallow.fields.AwareDateTime(format=None, *, default_timezone=None, **kwargs)[source]

A formatted aware datetime string.

Parameters:
  • format (str | None) – See DateTime.

  • default_timezone (dt.tzinfo | None) – 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.

Added in version 3.0.0rc9.

marshmallow.fields.Bool

alias of Boolean

class marshmallow.fields.Boolean(*, truthy=None, falsy=None, **kwargs)[source]

A boolean field.

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

Default falsy values.

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

Default truthy values.

class marshmallow.fields.Constant(constant, **kwargs)[source]

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 (Any) – The constant to return for the field attribute.

class marshmallow.fields.Date(format=None, **kwargs)[source]

ISO8601-formatted date string.

Parameters:
  • format (str | None) – 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.DateTime(format=None, **kwargs)[source]

A formatted datetime string.

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

Parameters:
  • format (str | None) – Either "rfc" (for RFC822), "iso" (for ISO8601), "timestamp", "timestamp_ms" (for a POSIX timestamp) 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.

Changed in version 3.19: Add timestamp as a format.

class marshmallow.fields.Decimal(places=None, rounding=None, *, allow_nan=False, as_string=False, **kwargs)[source]

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 (int | None) – How many decimal places to quantize the value. If None, does not quantize the value.

  • rounding (str | None) – 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 (bool) – If True, NaN, Infinity and -Infinity are allowed, even though they are illegal according to the JSON specification.

  • as_string (bool) – If True, serialize to a string instead of a Python decimal.Decimal type.

  • kwargs – The same keyword arguments that Number receives.

Added in version 1.2.0.

class marshmallow.fields.Dict(keys=None, values=None, **kwargs)[source]

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:

Added in version 2.1.0.

class marshmallow.fields.Email(*args, **kwargs)[source]

An email field.

Parameters:
  • args – The same positional arguments that String receives.

  • kwargs – The same keyword arguments that String receives.

class marshmallow.fields.Enum(enum, *, by_value=False, **kwargs)[source]

An Enum field (de)serializing enum members by symbol (name) or by value.

Parameters:
  • enum (type[EnumType]) – Enum class

  • by_value (bool | Field | type[Field]) – Whether to (de)serialize by value or by name, or Field class or instance to use to (de)serialize by value. Defaults to False.

If by_value is False (default), enum members are (de)serialized by symbol (name). If it is True, they are (de)serialized by value using Raw. If it is a field instance or class, they are (de)serialized by value using this field.

Added in version 3.18.0.

class marshmallow.fields.Float(*, allow_nan=False, as_string=False, **kwargs)[source]

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.

class marshmallow.fields.Function(serialize=None, deserialize=None, **kwargs)[source]

A field that takes the value returned by a function.

Parameters:
  • serialize (Callable[[Any], Any] | Callable[[Any, dict], Any] | None) – 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 (Callable[[Any], Any] | Callable[[Any, dict], Any] | None) – 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.

class marshmallow.fields.IP(*args, exploded=False, **kwargs)[source]

A IP address field.

Parameters:

exploded – If True, serialize ipv6 address in long form, ie. with groups consisting entirely of zeros included.

Added in version 3.8.0.

class marshmallow.fields.IPInterface(*args, exploded=False, **kwargs)[source]

A IPInterface field.

IP interface is the non-strict form of the IPNetwork type where arbitrary host addresses are always accepted.

IPAddress and mask e.g. ‘192.168.0.2/24’ or ‘192.168.0.2/255.255.255.0’

see https://python.readthedocs.io/en/latest/library/ipaddress.html#interface-objects

Parameters:

exploded (bool) – If True, serialize ipv6 interface in long form, ie. with groups consisting entirely of zeros included.

class marshmallow.fields.IPv4(*args, exploded=False, **kwargs)[source]

A IPv4 address field.

Added in version 3.8.0.

class marshmallow.fields.IPv4Interface(*args, exploded=False, **kwargs)[source]

A IPv4 Network Interface field.

Parameters:

exploded (bool)

class marshmallow.fields.IPv6(*args, exploded=False, **kwargs)[source]

A IPv6 address field.

Added in version 3.8.0.

class marshmallow.fields.IPv6Interface(*args, exploded=False, **kwargs)[source]

A IPv6 Network Interface field.

Parameters:

exploded (bool)

marshmallow.fields.Int

alias of Integer

class marshmallow.fields.Integer(*, strict=False, **kwargs)[source]

An integer field.

Parameters:
  • strict (bool) – If True, only integer types are valid. Otherwise, any value castable to int is valid.

  • kwargs – The same keyword arguments that Number receives.

class marshmallow.fields.List(cls_or_instance, **kwargs)[source]

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

Example:

numbers = fields.List(fields.Float())
Parameters:
  • cls_or_instance (Field | type[Field]) – A field class or instance.

  • kwargs – The same keyword arguments that Field receives.

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

class marshmallow.fields.Mapping(keys=None, values=None, **kwargs)[source]

An abstract class for objects with key-value pairs. This class should not be used within schemas.

Parameters:
  • keys (Field | type[Field] | None) – A field class or instance for dict keys.

  • values (Field | type[Field] | None) – 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.

Added in version 3.0.0rc4.

Changed in version 3.24.0: Mapping should no longer be used as a field within a Schema. Use Dict instead.

class marshmallow.fields.Method(serialize=None, deserialize=None, **kwargs)[source]

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

Parameters:
  • serialize (str | None) – 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 | None) – 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.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.

class marshmallow.fields.NaiveDateTime(format=None, *, timezone=None, **kwargs)[source]

A formatted naive datetime string.

Parameters:
  • format (str | None) – See DateTime.

  • timezone (dt.timezone | None) – 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.

Added in version 3.0.0rc9.

class marshmallow.fields.Nested(nested, *, dump_default=<marshmallow.missing>, default=<marshmallow.missing>, only=None, exclude=(), many=False, unknown=None, **kwargs)[source]

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 (Schema | SchemaMeta | str | dict[str, Field] | Callable[[], Schema | SchemaMeta | dict[str, Field]]) – Schema instance, class, class name (string), dictionary, or callable that returns a Schema or dictionary. Dictionaries are converted with Schema.from_dict.

  • exclude (types.StrSequenceOrSet) – A list or tuple of fields to exclude.

  • only (types.StrSequenceOrSet | None) – A list or tuple of fields to marshal. If None, all fields are marshalled. This parameter takes precedence over exclude.

  • many (bool) – Whether the field is a collection of objects.

  • unknown (str | None) – 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.

  • dump_default (Any)

  • default (Any)

property schema: Schema

The nested Schema object.

Changed in version 1.0.0: Renamed from serializer to schema.

class marshmallow.fields.Number(*, as_string=False, **kwargs)[source]

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.

Changed in version 3.24.0: Number should no longer be used as a field within a Schema. Use Integer, Float, or Decimal instead.

class marshmallow.fields.Pluck(nested, field_name, *, many=False, unknown=None, **kwargs)[source]

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 | SchemaMeta | str | Callable[[], 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.

  • many (bool)

  • unknown (str | None)

class marshmallow.fields.Raw(*, load_default=<marshmallow.missing>, missing=<marshmallow.missing>, dump_default=<marshmallow.missing>, default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None, **additional_metadata)[source]

Field that applies no formatting.

Parameters:
marshmallow.fields.Str

alias of String

class marshmallow.fields.String(*, load_default=<marshmallow.missing>, missing=<marshmallow.missing>, dump_default=<marshmallow.missing>, default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None, **additional_metadata)[source]

A string field.

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

  • load_default (Any)

  • missing (Any)

  • dump_default (Any)

  • default (Any)

  • data_key (str | None)

  • attribute (str | None)

  • validate (types.Validator | Iterable[types.Validator] | None)

  • required (bool)

  • allow_none (bool | None)

  • load_only (bool)

  • dump_only (bool)

  • error_messages (dict[str, str] | None)

  • metadata (Mapping[str, Any] | None)

class marshmallow.fields.Time(format=None, **kwargs)[source]

A formatted time string.

Example: '03:12:58.019077'

Parameters:
  • format (str | None) – 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='seconds', serialization_type=<class 'int'>, **kwargs)[source]

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

Parameters:
  • precision (str) – Influences how the integer or float is interpreted during (de)serialization. Must be ‘days’, ‘seconds’, ‘microseconds’, ‘milliseconds’, ‘minutes’, ‘hours’ or ‘weeks’.

  • serialization_type (type[int | float]) – Whether to (de)serialize to a int or float.

  • kwargs – The same keyword arguments that Field receives.

Integer Caveats

Any fractional parts (which depends on the precision used) will be truncated when serializing using int.

Float Caveats

Use of float when (de)serializing may result in data precision loss due to the way machines handle floating point values.

Regardless of the precision chosen, the fractional part when using float will always be truncated to microseconds. For example, 1.12345 interpreted as microseconds will result in timedelta(microseconds=1).

Changed in version 3.17.0: Allow (de)serialization to float through use of a new serialization_type parameter. int is the default to retain previous behaviour.

class marshmallow.fields.Tuple(tuple_fields, **kwargs)[source]

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:

Added in version 3.0.0rc4.

marshmallow.fields.URL

alias of Url

class marshmallow.fields.UUID(*, load_default=<marshmallow.missing>, missing=<marshmallow.missing>, dump_default=<marshmallow.missing>, default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None, **additional_metadata)[source]

A UUID field.

Parameters:
class marshmallow.fields.Url(*, relative=False, absolute=True, schemes=None, require_tld=True, **kwargs)[source]

An URL field.

Parameters:
  • default – Default value for the field if the attribute is not set.

  • relative (bool) – Whether to allow relative URLs.

  • absolute (bool) – Whether to allow absolute URLs.

  • require_tld (bool) – Whether to reject non-FQDN hostnames.

  • schemes (types.StrSequenceOrSet | None) – Valid schemes. By default, http, https, ftp, and ftps are allowed.

  • kwargs – The same keyword arguments that String receives.