Fields¶
Field classes for various types of data.
Classes
|
Basic field from which other fields should extend. |
|
Field that applies no formatting. |
|
Allows you to nest a |
|
An abstract class for objects with key-value pairs. |
|
A dict field. |
|
A list field, composed with another |
|
A tuple field, composed of a fixed number of other |
|
A string field. |
|
A UUID field. |
|
Base class for number fields. |
|
An integer field. |
|
A field that (de)serializes to the Python |
|
A boolean field. |
|
A double as an IEEE-754 double precision string. |
|
A formatted datetime string. |
|
A formatted naive datetime string. |
|
A formatted aware datetime string. |
|
ISO8601-formatted time string. |
|
ISO8601-formatted date string. |
|
A field that (de)serializes a |
|
A validated URL field. |
A validated URL field. |
|
|
A validated email field. |
|
A field that takes the value returned by a |
|
A field that takes the value returned by a function. |
A string field. |
|
A boolean field. |
|
An integer field. |
|
|
A field that (de)serializes to a preset constant. |
|
Allows you to replace nested data with one of the data’s fields. |
-
class
marshmallow.fields.AwareDateTime(format: str = None, *, default_timezone: datetime.timezone = None, **kwargs)[source]¶ A formatted aware datetime string.
- Parameters
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
New in version 3.0.0rc9.
-
_deserialize(value, attr, data, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
marshmallow.fields.Bool¶ alias of
marshmallow.fields.Boolean
|
Deserialize value. |
|
Serializes |
Methods
-
class
marshmallow.fields.Boolean(*, truthy: Set = None, falsy: Set = None, **kwargs)[source]¶ A boolean field.
- Parameters
truthy – 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 – Values that will (de)serialize to
False. IfNone,marshmallow.fields.Boolean.falsywill be used.kwargs – The same keyword arguments that
Fieldreceives.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
Default falsy values.
Default truthy values.
-
_deserialize(value, attr, data, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'invalid': 'Not a valid boolean.'}¶ Default error messages.
-
falsy= {'NO', 0, 'n', 'False', 'F', 'FALSE', 'off', 'No', 'Off', '0', 'N', 'false', 'f', 'no', 'OFF'}¶ Default falsy values.
-
truthy= {'YES', 'on', 1, 'Y', 't', 'ON', 'On', '1', 'T', 'true', 'TRUE', 'y', 'Yes', 'yes', 'True'}¶ Default truthy values.
-
class
marshmallow.fields.Constant(constant: Any, **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 – The constant to return for the field attribute.
Methods
_deserialize(value, *args, **kwargs)Deserialize value.
_serialize(value, *args, **kwargs)Serializes
valueto a basic Python datatype.New in version 2.0.0.
-
_deserialize(value, *args, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, *args, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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)[source]¶ ISO8601-formatted date string.
- Parameters
format – Either
"iso"(for ISO8601) or a date format string. IfNone, defaults to “iso”.kwargs – The same keyword arguments that
Fieldreceives.
Attributes
Default error messages.
-
default_error_messages= {'format': '"{input}" cannot be formatted as a date.', 'invalid': 'Not a valid date.'}¶ Default error messages.
-
class
marshmallow.fields.DateTime(format: str = None, **kwargs)[source]¶ 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. IfNone, defaults to “iso”.kwargs – The same keyword arguments that
Fieldreceives.
Methods
_bind_to_schema(field_name, schema)Update field with values from its parent schema.
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
Changed in version 3.0.0rc9: Does not modify timezone information on (de)serialization.
-
_bind_to_schema(field_name, schema)[source]¶ 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)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'format': '"{input}" cannot be formatted as a {obj_type}.', 'invalid': 'Not a valid {obj_type}.', 'invalid_awareness': 'Not a valid {awareness} {obj_type}.'}¶ Default error messages.
-
class
marshmallow.fields.Decimal(places: int = None, rounding: str = None, *, allow_nan: bool = False, as_string: bool = 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.Methods
_format_num(value)Return the number value for value, given this field’s
num_type._validated(value)Format the value or raise a
ValidationErrorif an error occurs.Attributes
Default error messages.
Classes
Construct a new Decimal object.
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 – 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. IfNone, uses the rounding value from the current thread’s context.allow_nan – If
True,NaN,Infinityand-Infinityare allowed, even though they are illegal according to the JSON specification.as_string – If
True, serialize to a string instead of a Pythondecimal.Decimaltype.kwargs – The same keyword arguments that
Numberreceives.
New in version 1.2.0.
-
default_error_messages= {'special': 'Special numeric values (nan or infinity) are not permitted.'}¶ Default error messages.
-
num_type¶ alias of
decimal.Decimal
-
class
marshmallow.fields.Dict(keys: Union[marshmallow.fields.Field, type] = None, values: Union[marshmallow.fields.Field, type] = 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())
Classes
dict() -> new empty dictionary
- Parameters
kwargs – The same keyword arguments that
Mappingreceives.
New in version 2.1.0.
-
mapping_type¶ alias of
builtins.dict
-
class
marshmallow.fields.Email(*args, **kwargs)[source]¶ A validated email field. Validation occurs during both serialization and deserialization.
- Parameters
Attributes
Default error messages.
-
default_error_messages= {'invalid': 'Not a valid email address.'}¶ Default error messages.
-
class
marshmallow.fields.Field(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]¶ 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
loadand the output ofdump. IfNone, 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 usedata_keyinstead.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, anValidationErroris raised.required – Raise a
ValidationErrorif the field value is not supplied during deserialization.allow_none – Set this to
TrueifNoneshould be considered a valid value during validation/deserialization. Ifmissing=Noneandallow_noneis unset, will default toTrue. Otherwise, the default isFalse.load_only – If
Trueskip this field during serialization, otherwise its value will be present in the serialized data.dump_only – 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 (dict) – Overrides for
Field.default_error_messages.metadata – Extra arguments to be stored as metadata.
Methods
_bind_to_schema(field_name, schema)Update field with values from its parent schema.
_deserialize(value, attr, data, Any]], **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype._validate(value)Perform validation on
value._validate_missing(value)Validate missing values.
deserialize(value, attr, data, Any] = None, …)Deserialize
value.fail(key, **kwargs)Helper method that raises a
ValidationErrorwith an error message fromself.error_messages.get_value(obj, attr[, accessor, default])Return the value for a given key from an object.
make_error(key, **kwargs)Helper method to make a
ValidationErrorwith an error message fromself.error_messages.serialize(attr, obj, accessor, str, Any], …)Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
Attributes
The context dictionary for the parent
Schema.Default error messages for various kinds of errors.
Reference to the
Schemathat this field belongs to even if it is buried in a container field (e.g.Changed in version 2.0.0: Removed
errorparameter. Useerror_messagesinstead.Changed in version 2.0.0: Added
allow_noneparameter, which makes validation/deserialization ofNoneconsistent across fields.Changed in version 2.0.0: Added
load_onlyanddump_onlyparameters, which allow field skipping during the (de)serialization process.Changed in version 2.0.0: Added
missingparameter, which indicates the value for a field if the field is not found during deserialization.Changed in version 2.0.0:
defaultvalue is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output.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.-
_bind_to_schema(field_name, schema)[source]¶ 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)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value: Any, attr: str, obj: Any, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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)[source]¶ Perform validation on
value. Raise aValidationErrorif validation does not succeed.
-
_validate_missing(value)[source]¶ Validate missing values. Raise a
ValidationErrorifvalueshould be considered missing.
-
property
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 tomarshmallow.exceptions.ValidationError.
-
deserialize(value: Any, attr: str = None, data: Mapping[str, Any] = None, **kwargs)[source]¶ Deserialize
value.- Parameters
value – The value to deserialize.
attr – The attribute/key in
datato 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)[source]¶ Helper method that raises a
ValidationErrorwith an error message fromself.error_messages.Deprecated since version 3.0.0: Use
make_errorinstead.
-
get_value(obj, attr, accessor=None, default=<marshmallow.missing>)[source]¶ 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
objto get the value from.accessor (callable) – A callable used to retrieve the value of
attrfrom the objectobj. Defaults tomarshmallow.utils.get_value.
-
make_error(key: str, **kwargs) → marshmallow.exceptions.ValidationError[source]¶ Helper method to make a
ValidationErrorwith an error message fromself.error_messages.
-
property
root¶ Reference to the
Schemathat this field belongs to even if it is buried in a container field (e.g.List). ReturnNonefor unbound fields.
-
serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] = None, **kwargs)[source]¶ 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.Float(*, allow_nan: bool = False, as_string: bool = 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 – The same keyword arguments that
Numberreceives.
Methods
_validated(value)Format the value or raise a
ValidationErrorif an error occurs.Attributes
Default error messages.
Classes
Convert a string or number to a floating point number, if possible.
-
default_error_messages= {'special': 'Special numeric values (nan or infinity) are not permitted.'}¶ Default error messages.
-
num_type¶ alias of
builtins.float
-
class
marshmallow.fields.Function(serialize: Union[Callable[[Any], Any], Callable[[Any, Dict], Any]] = None, deserialize: Union[Callable[[Any], Any], Callable[[Any, Dict], Any]] = None, **kwargs)[source]¶ 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
objwhich is the object to be serialized. It can also optionally take acontextargument, 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
valuewhich is the value to be deserialized. It can also optionally take acontextargument, which is a dictionary of context variables passed to the deserializer. If no callable is provided then`value`will be passed through unchanged.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Changed in version 2.3.0: Deprecated
funcparameter in favor ofserialize.Changed in version 3.0.0a1: Removed
funcparameter.-
_deserialize(value, attr, data, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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.Int¶ alias of
marshmallow.fields.Integer
|
int([x]) -> integer |
Methods
|
Format the value or raise a |
Classes
-
class
marshmallow.fields.Integer(*, strict: bool = False, **kwargs)[source]¶ An integer field.
- Parameters
strict – If
True, only integer types are valid. Otherwise, any value castable tointis valid.kwargs – The same keyword arguments that
Numberreceives.
Methods
_validated(value)Format the value or raise a
ValidationErrorif an error occurs.Attributes
Default error messages.
Classes
int([x]) -> integer
-
default_error_messages= {'invalid': 'Not a valid integer.'}¶ Default error messages.
-
num_type¶ alias of
builtins.int
-
class
marshmallow.fields.List(cls_or_instance: Union[marshmallow.fields.Field, type], **kwargs)[source]¶ A list field, composed with another
Fieldclass or instance.Example:
numbers = fields.List(fields.Float())
Methods
_bind_to_schema(field_name, schema)Update field with values from its parent schema.
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
- Parameters
cls_or_instance – A field class or instance.
kwargs – The same keyword arguments that
Fieldreceives.
Changed in version 2.0.0: The
allow_noneparameter 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)[source]¶ 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][source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs) → Optional[List[Any]][source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'invalid': 'Not a valid list.'}¶ Default error messages.
-
class
marshmallow.fields.Mapping(keys: Union[marshmallow.fields.Field, type] = None, values: Union[marshmallow.fields.Field, type] = None, **kwargs)[source]¶ 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
Fieldreceives.
Methods
_bind_to_schema(field_name, schema)Update field with values from its parent schema.
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
Classes
dict() -> new empty dictionary
Note
When the structure of nested data is not known, you may omit the
keysandvaluesarguments to prevent content validation.New in version 3.0.0rc4.
-
_bind_to_schema(field_name, schema)[source]¶ 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)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'invalid': 'Not a valid mapping type.'}¶ Default error messages.
-
mapping_type¶ alias of
builtins.dict
-
class
marshmallow.fields.Method(serialize: str = None, deserialize: str = None, **kwargs)[source]¶ A field that takes the value returned by a
Schemamethod.- 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.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Changed in version 2.0.0: Removed optional
contextparameter on methods. Useself.contextinstead.Changed in version 2.3.0: Deprecated
method_nameparameter in favor ofserializeand allowserializeto not be passed at all.Changed in version 3.0.0: Removed
method_nameparameter.-
_deserialize(value, attr, data, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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)[source]¶ A formatted naive datetime string.
- Parameters
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
New in version 3.0.0rc9.
-
_deserialize(value, attr, data, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
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)[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",)))
Methods
_deserialize(value, attr, data[, partial])Same as
Field._deserialize()with additionalpartialargument._serialize(nested_obj, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
The nested Schema object.
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 –
Schemainstance, class, class name (string), or callable that returns aSchemainstance.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 overexclude.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,INCLUDEorRAISE.kwargs – The same keyword arguments that
Fieldreceives.
-
_deserialize(value, attr, data, partial=None, **kwargs)[source]¶ Same as
Field._deserialize()with additionalpartialargument.- Parameters
partial (bool|tuple) – For nested schemas, the
partialparameter passed toSchema.load.
Changed in version 3.0.0: Add
partialparameter.
-
_serialize(nested_obj, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'type': 'Invalid type.'}¶ Default error messages.
-
class
marshmallow.fields.Number(*, as_string: bool = 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
Fieldreceives.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
_format_num(value)Return the number value for value, given this field’s
num_type._serialize(value, attr, obj, **kwargs)Return a string if
self.as_string=True, otherwise return this field’snum_type._validated(value)Format the value or raise a
ValidationErrorif an error occurs.Attributes
Default error messages.
Classes
Convert a string or number to a floating point number, if possible.
-
_deserialize(value, attr, data, **kwargs) → Optional[_T][source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs) → Optional[Union[str, _T]][source]¶ Return a string if
self.as_string=True, otherwise return this field’snum_type.
-
_validated(value) → Optional[_T][source]¶ Format the value or raise a
ValidationErrorif an error occurs.
-
default_error_messages= {'invalid': 'Not a valid number.', 'too_large': 'Number too large.'}¶ Default error messages.
-
num_type¶ alias of
builtins.float
-
class
marshmallow.fields.Pluck(nested: Union[marshmallow.base.SchemaABC, type, str, Callable[], marshmallow.base.SchemaABC]], field_name: str, **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}
Methods
_deserialize(value, attr, data[, partial])Same as
Field._deserialize()with additionalpartialargument._serialize(nested_obj, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.- Parameters
-
_deserialize(value, attr, data, partial=None, **kwargs)[source]¶ Same as
Field._deserialize()with additionalpartialargument.- Parameters
partial (bool|tuple) – For nested schemas, the
partialparameter passed toSchema.load.
Changed in version 3.0.0: Add
partialparameter.
-
_serialize(nested_obj, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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.Raw(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]¶ Field that applies no formatting.
-
marshmallow.fields.Str¶ alias of
marshmallow.fields.String
|
Deserialize value. |
|
Serializes |
Methods
-
class
marshmallow.fields.String(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]¶ A string field.
- Parameters
kwargs – The same keyword arguments that
Fieldreceives.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
-
_deserialize(value, attr, data, **kwargs) → Any[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs) → Optional[str][source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'}¶ Default error messages.
-
class
marshmallow.fields.Time(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]¶ ISO8601-formatted time string.
- Parameters
kwargs – The same keyword arguments that
Fieldreceives.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize an ISO8601-formatted time to a
datetime.timeobject._serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
-
_deserialize(value, attr, data, **kwargs)[source]¶ Deserialize an ISO8601-formatted time to a
datetime.timeobject.
-
_serialize(value, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'format': '"{input}" cannot be formatted as a time.', 'invalid': 'Not a valid time.'}¶ Default error messages.
-
class
marshmallow.fields.TimeDelta(precision: str = 'seconds', **kwargs)[source]¶ A field that (de)serializes a
datetime.timedeltaobject 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
Fieldreceives.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
Changed in version 2.0.0: Always serializes to an integer value to avoid rounding errors. Add
precisionparameter.-
_deserialize(value, attr, data, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'format': '{input!r} cannot be formatted as a timedelta.', 'invalid': 'Not a valid period of time.'}¶ Default error messages.
-
class
marshmallow.fields.Tuple(tuple_fields, *args, **kwargs)[source]¶ A tuple field, composed of a fixed number of other
Fieldclasses or instancesExample:
row = Tuple((fields.String(), fields.Integer(), fields.Float()))
Methods
_bind_to_schema(field_name, schema)Update field with values from its parent schema.
_deserialize(value, attr, data, **kwargs)Deserialize value.
_serialize(value, attr, obj, **kwargs)Serializes
valueto a basic Python datatype.Attributes
Default error messages.
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
New in version 3.0.0rc4.
-
_bind_to_schema(field_name, schema)[source]¶ 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[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_serialize(value, attr, obj, **kwargs) → Optional[Tuple][source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses 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
-
default_error_messages= {'invalid': 'Not a valid tuple.'}¶ Default error messages.
-
marshmallow.fields.URL¶ alias of
marshmallow.fields.Url
-
class
marshmallow.fields.UUID(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]¶ A UUID field.
Methods
_deserialize(value, attr, data, **kwargs)Deserialize value.
_validated(value)Format the value or raise a
ValidationErrorif an error occurs.Attributes
Default error messages.
-
_deserialize(value, attr, data, **kwargs) → Optional[uuid.UUID][source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in
datato 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
attranddataparameters.Changed in version 3.0.0: Added
**kwargsto signature.
-
_validated(value) → Optional[uuid.UUID][source]¶ Format the value or raise a
ValidationErrorif an error occurs.
-
default_error_messages= {'invalid_uuid': 'Not a valid UUID.'}¶ Default error messages.
-
-
class
marshmallow.fields.Url(*, relative: bool = False, schemes: Union[Sequence[str], Set[str]] = None, require_tld: bool = True, **kwargs)[source]¶ 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, andftpsare allowed.kwargs – The same keyword arguments that
Stringreceives.
Attributes
Default error messages.
-
default_error_messages= {'invalid': 'Not a valid URL.'}¶ Default error messages.