Fields¶
Base Field Class¶
- class marshmallow.fields.Field(*, load_default=<marshmallow.missing>, dump_default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, pre_load=None, post_load=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None)[source]¶
Base field from which all other fields inherit. This class should not be used directly within Schemas.
- 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
loadand the output ofdump. IfNone, 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
loadand the input ofdump. IfNone, 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 usedata_keyinstead.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, anValidationErroris raised.pre_load (types.PreLoadCallable | Iterable[types.PreLoadCallable] | None) – Callable or collection of callables that are applied to the raw input value before deserialization. Each callable receives the value and returns a transformed value.
post_load (types.PostLoadCallable | Iterable[types.PostLoadCallable] | None) – Callable or collection of callables that are applied to the deserialized value after validation. Each callable receives the value and returns a transformed value.
required (bool) – Raise a
ValidationErrorif the field value is not supplied during deserialization.allow_none (bool | None) – Set this to
TrueifNoneshould be considered a valid value during validation/deserialization. If set toFalse(the default),Noneis considered invalid input. Ifload_defaultis explicitly set toNoneandallow_noneis unset,allow_noneis implicitly set toTrue.load_only (bool) – If
Trueskip this field during serialization, otherwise its value will be present in the serialized data.dump_only (bool) – If
Trueskip 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 (types.ErrorMessages | None) – Overrides for
Field.default_error_messages.metadata (Mapping[str, Any] | None) – Extra information to be stored as field metadata.
Changed in version 3.0.0b8: Add
data_keyparameter for the specifying the key in the input and output data. This parameter replaced bothload_fromanddump_to.Changed in version 3.13.0: Replace
missinganddefaultparameters withload_defaultanddump_default.Changed in version 3.24.0:
Fieldshould no longer be used as a field within aSchema. UseRawor anotherFieldsubclass instead.Changed in version 4.0.0: Remove
contextproperty.Changed in version 4.3.0: Add
pre_loadandpost_load.
Field subclasses¶
Classes:
A formatted aware datetime string. |
|
alias of |
|
A boolean field. |
|
A field that (de)serializes to a preset constant. |
|
ISO8601-formatted date string. |
|
A formatted datetime string. |
|
A field that (de)serializes to the Python |
|
A dict field. |
|
An email field. |
|
An Enum field (de)serializing enum members by symbol (name) or by value. |
|
A double as an IEEE-754 double precision string. |
|
A field that takes the value returned by a function. |
|
A IP address field. |
|
A IPInterface field. |
|
A IPv4 address field. |
|
A IPv4 Network Interface field. |
|
A IPv6 address field. |
|
A IPv6 Network Interface field. |
|
alias of |
|
An integer field. |
|
A list field, composed with another |
|
Abstract base class for objects with key-value pairs. |
|
A field that takes the value returned by a |
|
A formatted naive datetime string. |
|
Allows you to nest a |
|
Abstract base class for number fields. |
|
Allows you to replace nested data with one of the data's fields. |
|
Field that applies no formatting. |
|
alias of |
|
A string field. |
|
A formatted time string. |
|
A field that (de)serializes a |
|
A tuple field, composed of a fixed number of other |
|
alias of |
|
A UUID field. |
|
An URL field. |
- class marshmallow.fields.AwareDateTime(format=None, *, default_timezone=None, **kwargs)[source]¶
A formatted aware datetime string.
- Parameters:
Added in version 3.0.0rc9.
- class marshmallow.fields.Boolean(*, truthy=None, falsy=None, **kwargs)[source]¶
A boolean field.
- Parameters:
truthy (Iterable | None) – Values that will (de)serialize to
True. If an empty set, any non-falsy value will deserialize toTrue. IfNone,marshmallow.fields.Boolean.truthywill be used.falsy (Iterable | None) – Values that will (de)serialize to
False. IfNone,marshmallow.fields.Boolean.falsywill be used.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
- 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=Trueorload_only=Truerespectively.- Parameters:
constant (_ContantT) – The constant to return for the field attribute.
kwargs (Unpack[_BaseFieldKwargs])
- 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. IfNone, defaults to “iso”.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
- 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. IfNone, defaults to “iso”.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
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.Decimaltype. 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.Decimalobject by default. If you need to render your data as JSON, keep in mind that thejsonmodule from the standard library does not encodedecimal.Decimal. Therefore, you must use a JSON library that can handle decimals, such assimplejson, or serialize to a string by passingas_string=True.Warning
If a JSON
floatvalue is passed to this field for deserialization it will first be cast to its correspondingstringvalue before being deserialized to adecimal.Decimalobject. The default__str__implementation of the built-in Pythonfloattype 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 JSONstringto 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. IfNone, uses the rounding value from the current thread’s context.allow_nan (bool) – If
True,NaN,Infinityand-Infinityare allowed, even though they are illegal according to the JSON specification.as_string (bool) – If
True, serialize to a string instead of a Pythondecimal.Decimaltype.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Numberreceives.
- class marshmallow.fields.Dict(keys=None, values=None, **kwargs)[source]¶
A dict field. Supports dicts and dict-like objects
Example:
numbers = fields.Dict(keys=fields.Str(), values=fields.Float())
- Parameters:
Added in version 2.1.0.
- class marshmallow.fields.Enum(enum, *, by_value=False, **kwargs)[source]¶
An Enum field (de)serializing enum members by symbol (name) or by value.
- Parameters:
If
by_valueisFalse(default), enum members are (de)serialized by symbol (name). If it isTrue, they are (de)serialized by value usingmarshmallow.fields.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,Infinityand-Infinityare allowed, even though they are illegal according to the JSON specification.as_string (bool) – If
True, format the value as a string.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Numberreceives.
- 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
objwhich is the object to be serialized. 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
valuewhich is the value to be deserialized. If no callable is provided then`value`will be passed through unchanged.kwargs (Unpack[_BaseFieldKwargs])
Changed in version 3.0.0a1: Removed
funcparameter.Changed in version 4.0.0: Don’t pass context to serialization and deserialization functions.
- class marshmallow.fields.IP(*, exploded=False, **kwargs)[source]¶
A IP address field.
- Parameters:
exploded (bool) – If
True, serialize ipv6 address in long form, ie. with groups consisting entirely of zeros included.kwargs (Unpack[_BaseFieldKwargs])
Added in version 3.8.0.
- class marshmallow.fields.IPInterface(*, 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.kwargs (Unpack[_BaseFieldKwargs])
- class marshmallow.fields.IPv4(*, exploded=False, **kwargs)[source]¶
A IPv4 address field.
Added in version 3.8.0.
- Parameters:
exploded (bool)
kwargs (Unpack[_BaseFieldKwargs])
- class marshmallow.fields.IPv4Interface(*, exploded=False, **kwargs)[source]¶
A IPv4 Network Interface field.
- Parameters:
exploded (bool)
kwargs (Unpack[_BaseFieldKwargs])
- class marshmallow.fields.IPv6(*, exploded=False, **kwargs)[source]¶
A IPv6 address field.
Added in version 3.8.0.
- Parameters:
exploded (bool)
kwargs (Unpack[_BaseFieldKwargs])
- class marshmallow.fields.IPv6Interface(*, exploded=False, **kwargs)[source]¶
A IPv6 Network Interface field.
- Parameters:
exploded (bool)
kwargs (Unpack[_BaseFieldKwargs])
- class marshmallow.fields.Integer(*, strict=False, as_string=False, **kwargs)[source]¶
An integer field.
- Parameters:
strict (bool) – If
True, only integer types are valid. Otherwise, any value castable tointis valid.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Numberreceives.as_string (bool)
- class marshmallow.fields.List(cls_or_instance, **kwargs)[source]¶
A list field, composed with another
Fieldclass or instance.Example:
numbers = fields.List(fields.Float())
- Parameters:
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]¶
Abstract base class for objects with key-value pairs.
Use
Dictwithin schemas.- Parameters:
Note
When the structure of nested data is not known, you may omit the
keysandvaluesarguments to prevent content validation.Added in version 3.0.0rc4.
- class marshmallow.fields.Method(serialize=None, deserialize=None, **kwargs)[source]¶
A field that takes the value returned by a
Schemamethod.- 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.kwargs (Unpack[_BaseFieldKwargs])
Changed in version 3.0.0: Removed
method_nameparameter.
- 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 notNone, aware datetimes are converted to this timezone before their timezone information is removed.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
Added in version 3.0.0rc9.
- class marshmallow.fields.Nested(nested, *, only=None, exclude=(), many=None, unknown=None, **kwargs)[source]¶
Allows you to nest a
Schemainside 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
Schemainstance as the first argument, the instance’sexclude,only, andmanyattributes will be respected.Therefore, when passing the
exclude,only, ormanyarguments tofields.Nested, you should pass aSchemaclass (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 | str | dict[str, Field]]) –
Schemainstance, class, class name (string), dictionary, or callable that returns aSchemaor dictionary. Dictionaries are converted withSchema.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 overexclude.many (bool | None) – Whether the field is a collection of objects. If
None(default), and nestedSchemainstance is provided,manyis not overridden. IfNone(default), andSchemasubclass is provided, schema instance setsmanyas False. IfTrue | Falsenested[nested_field].schema.manyis overridden.unknown (types.UnknownOption | None) – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
- class marshmallow.fields.Number(*, as_string=False, **kwargs)[source]¶
Abstract base class for number fields.
Use
Integer,Float, orDecimalwithin schemas.- Parameters:
as_string (bool) – If
True, format the serialized value as a string.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
- 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:
- class marshmallow.fields.Raw(*, load_default=<marshmallow.missing>, dump_default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, pre_load=None, post_load=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None)[source]¶
Field that applies no formatting.
- Parameters:
load_default (Any)
dump_default (Any)
data_key (str | None)
attribute (str | None)
validate (types.Validator | Iterable[types.Validator] | None)
pre_load (types.PreLoadCallable | Iterable[types.PreLoadCallable] | None)
post_load (types.PostLoadCallable | Iterable[types.PostLoadCallable] | None)
required (bool)
allow_none (bool | None)
load_only (bool)
dump_only (bool)
error_messages (types.ErrorMessages | None)
metadata (Mapping[str, Any] | None)
- class marshmallow.fields.String(*, load_default=<marshmallow.missing>, dump_default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, pre_load=None, post_load=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None)[source]¶
A string field.
- Parameters:
kwargs – The same keyword arguments that
Fieldreceives.load_default (Any)
dump_default (Any)
data_key (str | None)
attribute (str | None)
validate (types.Validator | Iterable[types.Validator] | None)
pre_load (types.PreLoadCallable | Iterable[types.PreLoadCallable] | None)
post_load (types.PostLoadCallable | Iterable[types.PostLoadCallable] | None)
required (bool)
allow_none (bool | None)
load_only (bool)
dump_only (bool)
error_messages (types.ErrorMessages | 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. IfNone, defaults to “iso”.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
- class marshmallow.fields.TimeDelta(precision='seconds', **kwargs)[source]¶
A field that (de)serializes a
datetime.timedeltaobject to afloat. Thefloatcan represent any time unit that thedatetime.timedeltaconstructor supports.- Parameters:
precision (str) – The time unit used for (de)serialization. Must be one of ‘weeks’, ‘days’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ or ‘microseconds’.
kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Fieldreceives.
Float Caveats¶
Precision loss may occur when serializing a highly precise
datetime.timedeltaobject using a bigprecisionunit due to floating point arithmetics.When necessary, the
datetime.timedeltaconstructor roundsfloatinputs to whole microseconds during initialization of the object. As a result, deserializing afloatmight be subject to rounding, regardless ofprecision. For example,TimeDelta().deserialize("1.1234567") == timedelta(seconds=1, microseconds=123457).Changed in version 3.17.0: Allow serialization to
floatthrough use of a newserialization_typeparameter. Defaults tointfor backwards compatibility. Also affects deserialization.Changed in version 4.0.0: Remove
serialization_typeparameter and always serialize to float. Value is cast to afloatupon deserialization.
- class marshmallow.fields.Tuple(tuple_fields, **kwargs)[source]¶
A tuple field, composed of a fixed number of other
Fieldclasses or instancesExample:
row = Tuple((fields.String(), fields.Integer(), fields.Float()))
Note
Because of the structured nature of
collections.namedtupleandtyping.NamedTuple, using a Schema within a Nested field for them is more appropriate than using aTuplefield.- Parameters:
Added in version 3.0.0rc4.
- class marshmallow.fields.UUID(*, load_default=<marshmallow.missing>, dump_default=<marshmallow.missing>, data_key=None, attribute=None, validate=None, pre_load=None, post_load=None, required=False, allow_none=None, load_only=False, dump_only=False, error_messages=None, metadata=None)[source]¶
A UUID field.
- Parameters:
load_default (Any)
dump_default (Any)
data_key (str | None)
attribute (str | None)
validate (types.Validator | Iterable[types.Validator] | None)
pre_load (types.PreLoadCallable | Iterable[types.PreLoadCallable] | None)
post_load (types.PostLoadCallable | Iterable[types.PostLoadCallable] | None)
required (bool)
allow_none (bool | None)
load_only (bool)
dump_only (bool)
error_messages (types.ErrorMessages | None)
metadata (Mapping[str, Any] | None)
- 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, andftpsare allowed.kwargs (Unpack[_BaseFieldKwargs]) – The same keyword arguments that
Stringreceives.