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 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
load
and 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_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
, anValidationError
is raised.required (bool) – Raise a
ValidationError
if the field value is not supplied during deserialization.allow_none (bool | None) – Set this to
True
ifNone
should be considered a valid value during validation/deserialization. If set toFalse
(the default),None
is considered invalid input. Ifload_default
is explicitly set toNone
andallow_none
is unset,allow_none
is implicitly set toTrue
.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 bothload_from
anddump_to
.Changed in version 3.13.0: Replace
missing
anddefault
parameters withload_default
anddump_default
.
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 |
|
An abstract 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 |
|
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.truthy
will be used.falsy (Iterable | None) – Values that will (de)serialize to
False
. IfNone
,marshmallow.fields.Boolean.falsy
will be used.kwargs – The same keyword arguments that
Field
receives.
- 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
orload_only=True
respectively.- Parameters:
constant (Any) – The constant to return for the field attribute.
- class marshmallow.fields.DateTime(format=None, **kwargs)[source]¶
A formatted datetime string.
Example:
'2014-12-22T03:12:58.019077+00:00'
- Parameters:
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 thejson
module 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
float
value is passed to this field for deserialization it will first be cast to its correspondingstring
value before being deserialized to adecimal.Decimal
object. The default__str__
implementation of the built-in Pythonfloat
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 JSONstring
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
. IfNone
, 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 Pythondecimal.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.Enum(enum, *, by_value=False, **kwargs)[source]¶
An Enum field (de)serializing enum members by symbol (name) or by value.
- Parameters:
If
by_value
isFalse
(default), enum members are (de)serialized by symbol (name). If it isTrue
, they are (de)serialized by value usingRaw
. 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.
- 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 acontext
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 acontext
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 ofserialize
.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
- 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)
- 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:
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:
Note
When the structure of nested data is not known, you may omit the
keys
andvalues
arguments 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
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 ofserialize
and allowserialize
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:
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’sexclude
,only
, andmany
attributes will be respected.Therefore, when passing the
exclude
,only
, ormany
arguments tofields.Nested
, you should pass aSchema
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 aSchema
or 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) – 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
orRAISE
.kwargs – The same keyword arguments that
Field
receives.dump_default (Any)
default (Any)
- class marshmallow.fields.Number(*, as_string=False, **kwargs)[source]¶
Base class for number fields.
- 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>, 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.
- 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)
- class marshmallow.fields.Time(format=None, **kwargs)[source]¶
A formatted time string.
Example:
'03:12:58.019077'
- 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
orfloat
.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 intimedelta(microseconds=1)
.
- class marshmallow.fields.Tuple(tuple_fields, **kwargs)[source]¶
A tuple field, composed of a fixed number of other
Field
classes or instancesExample:
row = Tuple((fields.String(), fields.Integer(), fields.Float()))
Note
Because of the structured nature of
collections.namedtuple
andtyping.NamedTuple
, using a Schema within a Nested field for them is more appropriate than using aTuple
field.- Parameters:
Added in version 3.0.0rc4.
- 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.
- 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
, andftps
are allowed.kwargs – The same keyword arguments that
String
receives.