Top-level API¶
Classes:
Base schema class with which to define schemas. |
|
Defines defaults for |
Exceptions:
Raised when validation fails on a field or schema. |
Functions:
Register a method to invoke after serializing an object. |
|
Register a method to invoke after deserializing an object. |
|
Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. |
|
Register a method to invoke before serializing an object. |
|
Register a method to invoke before deserializing an object. |
|
Register a field validator. |
|
Register a schema-level validator. |
- class marshmallow.Schema(*, only=None, exclude=(), many=None, context=None, load_only=(), dump_only=(), partial=None, unknown=None)[source]¶
Base schema class with which to define schemas.
Example usage:
import datetime as dt from dataclasses import dataclass from marshmallow import Schema, fields @dataclass class Album: title: str release_date: dt.date class AlbumSchema(Schema): title = fields.Str() release_date = fields.Date() album = Album("Beggars Banquet", dt.date(1968, 12, 6)) schema = AlbumSchema() data = schema.dump(album) data # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}
- Parameters:
only (types.StrSequenceOrSet | None) – Whitelist of the declared fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters.
exclude (types.StrSequenceOrSet) – Blacklist of the declared fields to exclude when instantiating the Schema. If a field appears in both
onlyandexclude, it is not used. Nested fields can be represented with dot delimiters.many (bool | None) – Should be set to
Trueifobjis a collection so that the object will be serialized to a list.context (dict | None) – Optional context passed to
fields.Methodandfields.Functionfields.load_only (types.StrSequenceOrSet) – Fields to skip during serialization (write-only fields)
dump_only (types.StrSequenceOrSet) – Fields to skip during deserialization (read-only fields)
partial (bool | types.StrSequenceOrSet | None) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown (str | None) – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE.
Changed in version 3.0.0:
prefixparameter removed.- class Meta[source]¶
Options object for a Schema.
Example usage:
from marshmallow import Schema class MySchema(Schema): class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
A note on type checking
Type checkers will only check the attributes of the
Metaclass if you explicitly subclassmarshmallow.Schema.Meta.from marshmallow import Schema class MySchema(Schema): # Not checked by type checkers class Meta: additional = True class MySchema2(Schema): # Type checkers will check attributes class Meta(Schema.Meta): additional = True # Incompatible types in assignment
Removed in version 3.0.0b7: Remove
strict.Added in version 3.0.0b12: Add
unknown.Changed in version 3.0.0b17: Rename
dateformattodatetimeformat.Added in version 3.9.0: Add
timeformat.Changed in version 3.26.0: Deprecate
ordered. Field order is preserved by default.- additional: ClassVar[tuple[str, ...] | list[str]]¶
Fields to include in addition to the explicitly declared fields.
additionalandfieldsare mutually-exclusive options.
- dump_only: ClassVar[tuple[str, ...] | list[str]]¶
Fields to exclude from serialized results
- exclude: ClassVar[tuple[str, ...] | list[str]]¶
Fields to exclude in the serialized result. Nested fields can be represented with dot delimiters.
- fields: ClassVar[tuple[str, ...] | list[str]]¶
Fields to include in the (de)serialized result
- include: ClassVar[dict[str, Field]]¶
Dictionary of additional fields to include in the schema. It is usually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords.
- index_errors: ClassVar[bool]¶
If
True, errors dictionaries will include the index of invalid items in a collection.
- load_only: ClassVar[tuple[str, ...] | list[str]]¶
Fields to exclude from serialized results
- many: ClassVar[bool]¶
Whether data should be (de)serialized as a collection by default.
- ordered: ClassVar[bool]¶
If
True,Schema.dumpis acollections.OrderedDict.
- property dict_class: type[dict]¶
dicttype to return when serializing.
- dump(obj, *, many=None)[source]¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj (Any) – The object to serialize.
many (bool | None) – Whether to serialize
objas a collection. IfNone, the value forself.manyis used.
- Returns:
Serialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj, *args, many=None, **kwargs)[source]¶
Same as
dump(), except return a JSON-encoded string.- Parameters:
obj (Any) – The object to serialize.
many (bool | None) – Whether to serialize
objas a collection. IfNone, the value forself.manyis used.
- Returns:
A
jsonstring
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.
- error_messages: dict[str, str] = {}¶
Overrides for default schema-level error messages
- classmethod from_dict(fields, *, name='GeneratedSchema')[source]¶
Generate a
Schemaclass given a dictionary of fields.from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in
Nestedfields.- Parameters:
fields (dict[str, Field]) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
reprfor the class.
- Return type:
type[Schema]
Added in version 3.0.0.
- get_attribute(obj, attr, default)[source]¶
Defines how to pull values from an object to serialize.
Changed in version 3.0.0a1: Changed position of
objandattr.- Parameters:
obj (Any)
attr (str)
default (Any)
- handle_error(error, data, *, many, **kwargs)[source]¶
Custom error handler function for the schema.
- Parameters:
error (ValidationError) – The
ValidationErrorraised during (de)serialization.data (Any) – The original input data.
many (bool) – Value of
manyon dump or load.partial – Value of
partialon load.
Changed in version 3.0.0rc9: Receives
manyandpartial(on deserialization) as keyword arguments.
- load(data, *, many=None, partial=None, unknown=None)[source]¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters:
data (Mapping[str, Any] | Iterable[Mapping[str, Any]]) – The data to deserialize.
many (bool | None) – Whether to deserialize
dataas a collection. IfNone, the value forself.manyis used.partial (bool | Sequence[str] | AbstractSet[str] | None) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown (str | None) – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE. IfNone, the value forself.unknownis used.
- Returns:
Deserialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- loads(json_data, *, many=None, partial=None, unknown=None, **kwargs)[source]¶
Same as
load(), except it usesmarshmallow.Schema.Meta.render_moduleto deserialize the passed string before passing data toload().- Parameters:
json_data (str | bytes | bytearray) – A string of the data to deserialize.
many (bool | None) – Whether to deserialize
objas a collection. IfNone, the value forself.manyis used.partial (bool | Sequence[str] | AbstractSet[str] | None) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown (str | None) – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE. IfNone, the value forself.unknownis used.
- Returns:
Deserialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- on_bind_field(field_name, field_obj)[source]¶
Hook to modify a field when it is bound to the
Schema.No-op by default.
- Parameters:
field_name (str)
field_obj (Field)
- Return type:
None
- set_class¶
alias of
OrderedSet
- validate(data, *, many=None, partial=None)[source]¶
Validate
dataagainst the schema, returning a dictionary of validation errors.- Parameters:
data (Mapping[str, Any] | Iterable[Mapping[str, Any]]) – The data to validate.
many (bool | None) – Whether to validate
dataas a collection. IfNone, the value forself.manyis used.partial (bool | Sequence[str] | AbstractSet[str] | None) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns:
A dictionary of validation errors.
- Return type:
dict[str, list[str]]
Added in version 1.1.0.
- class marshmallow.SchemaOpts(meta, ordered=False)[source]¶
Defines defaults for
marshmallow.Schema.Meta.- Parameters:
meta (type)
ordered (bool)
- exception marshmallow.ValidationError(message, field_name='_schema', data=None, valid_data=None, **kwargs)[source]¶
Raised when validation fails on a field or schema.
Validators and custom fields should raise this exception.
- Parameters:
message (str | list | dict) – An error message, list of error messages, or dict of error messages. If a dict, the keys are subitems and the values are error messages.
field_name (str) – Field name to store the error on. If
None, the error is stored as schema-level error.data (Mapping[str, Any] | Iterable[Mapping[str, Any]] | None) – Raw input data.
valid_data (list[dict[str, Any]] | dict[str, Any] | None) – Valid (de)serialized data.
- marshmallow.post_dump(fn=None, pass_many=False, pass_original=False)[source]¶
Register a method to invoke after serializing an object. The method receives the serialized object and returns the processed object.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sdump()call. Ifpass_many=True, the raw data (which may be a collection) is passed.If
pass_original=True, the original data (before serializing) will be passed as an additional argument to the method.Changed in version 3.0.0:
manyis always passed as a keyword arguments to the decorated method.- Parameters:
fn (Callable[[...], Any] | None)
pass_many (bool)
pass_original (bool)
- Return type:
Callable[[…], Any]
- marshmallow.post_load(fn=None, pass_many=False, pass_original=False)[source]¶
Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sload()call. Ifpass_many=True, the raw data (which may be a collection) is passed.If
pass_original=True, the original data (before deserializing) will be passed as an additional argument to the method.Changed in version 3.0.0:
partialandmanyare always passed as keyword arguments to the decorated method.- Parameters:
fn (Callable[[...], Any] | None)
pass_many (bool)
pass_original (bool)
- Return type:
Callable[[…], Any]
- marshmallow.pprint(obj, *args, **kwargs)[source]¶
Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. Useful for printing the output of
marshmallow.Schema.dump().Deprecated since version 3.7.0: marshmallow.pprint will be removed in marshmallow 4.
- Return type:
None
- marshmallow.pre_dump(fn=None, pass_many=False)[source]¶
Register a method to invoke before serializing an object. The method receives the object to be serialized and returns the processed object.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sdump()call. Ifpass_many=True, the raw data (which may be a collection) is passed.Changed in version 3.0.0:
manyis always passed as a keyword arguments to the decorated method.- Parameters:
fn (Callable[[...], Any] | None)
pass_many (bool)
- Return type:
Callable[[…], Any]
- marshmallow.pre_load(fn=None, pass_many=False)[source]¶
Register a method to invoke before deserializing an object. The method receives the data to be deserialized and returns the processed data.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sload()call. Ifpass_many=True, the raw data (which may be a collection) is passed.Changed in version 3.0.0:
partialandmanyare always passed as keyword arguments to the decorated method.- Parameters:
fn (Callable[[...], Any] | None)
pass_many (bool)
- Return type:
Callable[[…], Any]
- marshmallow.validates(field_name)[source]¶
Register a field validator.
- Parameters:
field_name (str) – Name of the field that the method validates.
- Return type:
Callable[[…], Any]
- marshmallow.validates_schema(fn=None, pass_many=False, pass_original=False, skip_on_field_errors=True)[source]¶
Register a schema-level validator.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’svalidate()call. Ifpass_many=True, the raw data (which may be a collection) is passed.If
pass_original=True, the original data (before unmarshalling) will be passed as an additional argument to the method.If
skip_on_field_errors=True, this validation method will be skipped whenever validation errors have been detected when validating fields.Changed in version 3.0.0b1:
skip_on_field_errorsdefaults toTrue.Changed in version 3.0.0:
partialandmanyare always passed as keyword arguments to the decorated method.- Parameters:
fn (Callable[[...], Any] | None)
pass_many (bool)
pass_original (bool)
skip_on_field_errors (bool)
- Return type:
Callable[[…], Any]
- marshmallow.EXCLUDE¶
- marshmallow.INCLUDE¶
- marshmallow.RAISE¶
- marshmallow.missing¶