Schema¶
- class marshmallow.schema.Schema(*, only=None, exclude=(), many=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
only
andexclude
, it is not used. Nested fields can be represented with dot delimiters.many (bool | None) – Should be set to
True
ifobj
is a collection so that the object will be serialized to a list.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
Nested
fields 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 (types.UnknownOption | None) – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE
,INCLUDE
orRAISE
.
Changed in version 3.0.0: Remove
prefix
parameter.Changed in version 4.0.0: Remove
context
parameter.Classes:
Options object for a Schema.
dict
type to return when serializing.alias of
OrderedSet
Methods:
Serialize an object to native Python data types according to this Schema's fields.
Same as
dump()
, except return a JSON-encoded string.Generate a
Schema
class given a dictionary of fields.Defines how to pull values from an object to serialize.
Custom error handler function for the schema.
Deserialize a data structure to an object defined by this Schema's fields.
Same as
load()
, except it usesmarshmallow.Schema.Meta.render_module
to deserialize the passed string before passing data toload()
.Hook to modify a field when it is bound to the
Schema
.Validate
data
against the schema, returning a dictionary of validation errors.Attributes:
Overrides for default schema-level error messages
Dictionary mapping field_names ->
Field
objects- 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
Meta
class 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.Opts): 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
dateformat
todatetimeformat
.Added in version 3.9.0: Add
timeformat
.Changed in version 3.26.0: Deprecate
ordered
. Field order is preserved by default.Removed in version 4.0.0: Remove
ordered
.Attributes:
Fields to include in addition to the explicitly declared fields.
Default format for
Date
fields.Default format for
DateTime
fields.Fields to exclude from serialized results
Fields to exclude in the serialized result.
Fields to include in the (de)serialized result
Dictionary of additional fields to include in the schema.
If
True
, errors dictionaries will include the index of invalid items in a collection.Fields to exclude from serialized results
Whether data should be (de)serialized as a collection by default.
Whether to register the
Schema
with marshmallow's internal class registry.Default format for
Time
fields.Whether to exclude, include, or raise an error for unknown fields in the data.
- additional: ClassVar[tuple[str, ...] | list[str]]¶
Fields to include in addition to the explicitly declared fields.
additional
andfields
are mutually-exclusive options.
- exclude: ClassVar[tuple[str, ...] | list[str]]¶
Fields to exclude in the serialized result. Nested fields can be represented with dot delimiters.
- 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.
- dump(obj, *, many=None)[source]¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
- Returns:
Serialized data
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is 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:
- Returns:
A
json
string
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- classmethod from_dict(fields, *, name='GeneratedSchema')[source]¶
Generate a
Schema
class 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
Nested
fields.- Parameters:
- Return type:
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
obj
andattr
.
- handle_error(error, data, *, many, **kwargs)[source]¶
Custom error handler function for the schema.
- Parameters:
error (ValidationError) – The
ValidationError
raised during (de)serialization.data (Any) – The original input data.
many (bool) – Value of
many
on dump or load.partial – Value of
partial
on load.
Changed in version 3.0.0rc9: Receives
many
andpartial
(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] | Sequence[Mapping[str, Any]]) – The data to deserialize.
many (bool | None) – Whether to deserialize
data
as a collection. IfNone
, the value forself.many
is used.partial (bool | Sequence[str] | AbstractSet[str] | None) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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 (Literal['exclude', 'include', 'raise'] | None) – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE
,INCLUDE
orRAISE
. IfNone
, the value forself.unknown
is used.
- Returns:
Deserialized data
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(s, /, *, many=None, partial=None, unknown=None, **kwargs)[source]¶
Same as
load()
, except it usesmarshmallow.Schema.Meta.render_module
to deserialize the passed string before passing data toload()
.- Parameters:
s (str | bytes | bytearray) – A string of the data to deserialize.
many (bool | None) – Whether to deserialize
obj
as a collection. IfNone
, the value forself.many
is used.partial (bool | Sequence[str] | AbstractSet[str] | None) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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 (Literal['exclude', 'include', 'raise'] | None) – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE
,INCLUDE
orRAISE
. IfNone
, the value forself.unknown
is used.
- Returns:
Deserialized data
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.Changed in version 4.0.0: Rename
json_module
parameter tos
.
- on_bind_field(field_name, field_obj)[source]¶
Hook to modify a field when it is bound to the
Schema
.No-op by default.
- set_class¶
alias of
OrderedSet
- validate(data, *, many=None, partial=None)[source]¶
Validate
data
against the schema, returning a dictionary of validation errors.- Parameters:
data (Mapping[str, Any] | Sequence[Mapping[str, Any]]) – The data to validate.
many (bool | None) – Whether to validate
data
as a collection. IfNone
, the value forself.many
is used.partial (bool | Sequence[str] | AbstractSet[str] | None) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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:
- class marshmallow.schema.SchemaOpts(meta)[source]¶
Defines defaults for
marshmallow.Schema.Meta
.- Parameters:
meta (type)