API Reference¶
- Schema
- Fields
- Decorators
- Validators
- Utility Functions
callable_or_raise()
from_iso_date()
from_iso_datetime()
from_iso_time()
from_rfc()
get_fixed_timezone()
get_func_args()
get_value()
is_collection()
is_generator()
is_instance_or_subclass()
is_iterable_but_not_string()
is_keyed_tuple()
isoformat()
pluck()
pprint()
resolve_field_instance()
rfcformat()
set_value()
timedelta_to_microseconds()
- Error Store
- Class Registry
- Exceptions
Classes:
|
Base schema class with which to define custom schemas. |
|
class Meta options for the |
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: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool | None = None, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]¶
Base schema class with which to define custom 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 – 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 – 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 – Should be set to
True
ifobj
is a collection so that the object will be serialized to a list.context – Optional context passed to
fields.Method
andfields.Function
fields.load_only – Fields to skip during serialization (write-only fields)
dump_only – Fields to skip during deserialization (read-only fields)
partial – 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 – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE
,INCLUDE
orRAISE
.
Changed in version 3.0.0:
prefix
parameter removed.Changed in version 2.0.0:
__validators__
,__preprocessors__
, and__data_handlers__
are removed in favor ofmarshmallow.decorators.validates_schema
,marshmallow.decorators.pre_load
andmarshmallow.decorators.post_dump
.__accessor__
and__error_handler__
are deprecated. Implement thehandle_error
andget_attribute
methods instead.Classes:
Meta
()Options object for a Schema.
alias of
SchemaOpts
alias of
OrderedSet
Attributes:
Overrides for default schema-level error messages
Dictionary mapping field_names ->
Field
objectsMethods:
dump
(obj, *[, many])Serialize an object to native Python data types according to this Schema's fields.
dumps
(obj, *args[, many])Same as
dump()
, except return a JSON-encoded string.from_dict
(fields, *[, name])Generate a
Schema
class given a dictionary of fields.get_attribute
(obj, attr, default)Defines how to pull values from an object to serialize.
handle_error
(error, data, *, many, **kwargs)Custom error handler function for the schema.
load
(data, *[, many, partial, unknown])Deserialize a data structure to an object defined by this Schema's fields.
loads
(json_data, *[, many, partial, unknown])Same as
load()
, except it takes a JSON string as input.on_bind_field
(field_name, field_obj)Hook to modify a field when it is bound to the
Schema
.validate
(data, *[, many, partial])Validate
data
against the schema, returning a dictionary of validation errors.- class Meta[source]¶
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an
OrderedDict
.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
many
: Whether the data is a collection by default.dateformat
: Default format forDate
fields.datetimeformat
: Default format forDateTime
fields.timeformat
: Default format forTime
fields.ordered
: IfTrue
, output ofSchema.dump
will be acollections.OrderedDict
.index_errors
: IfTrue
, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserialization
- OPTIONS_CLASS¶
alias of
SchemaOpts
- TYPE_MAPPING: Dict[type, Type[Field]] = {<class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'str'>: <class 'marshmallow.fields.String'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>}¶
- dump(obj: Any, *, many: bool | None = None)[source]¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj – The object to serialize.
many – Whether to serialize
obj
as a collection. IfNone
, the value forself.many
is 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. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)[source]¶
Same as
dump()
, except return a JSON-encoded string.- Parameters:
obj – The object to serialize.
many – Whether to serialize
obj
as a collection. IfNone
, the value forself.many
is used.
- Returns:
A
json
string
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- exclude: set[Any] | MutableSet[Any]¶
- classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type [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:
Added in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)[source]¶
Defines how to pull values from an object to serialize.
Added in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)[source]¶
Custom error handler function for the schema.
- Parameters:
error – The
ValidationError
raised during (de)serialization.data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
Added in version 2.0.0.
Changed in version 3.0.0rc9: Receives
many
andpartial
(on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters:
data – The data to deserialize.
many – Whether to deserialize
data
as a collection. IfNone
, the value forself.many
is used.partial – 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 – 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
Added in version 1.0.0.
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(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)[source]¶
Same as
load()
, except it takes a JSON string as input.- Parameters:
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize
obj
as a collection. IfNone
, the value forself.many
is used.partial – 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 – 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
Added in version 1.0.0.
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.
- on_bind_field(field_name: str, field_obj: Field) None [source]¶
Hook to modify a field when it is bound to the
Schema
.No-op by default.
- opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>¶
- set_class¶
alias of
OrderedSet
Methods:add
(key)Add an element.
discard
(key)Remove an element.
pop
([last])Return the popped value.
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None) dict[str, list[str]] [source]¶
Validate
data
against the schema, returning a dictionary of validation errors.- Parameters:
data – The data to validate.
many – Whether to validate
data
as a collection. IfNone
, the value forself.many
is used.partial – 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.
Added in version 1.1.0.
- class marshmallow.SchemaOpts(meta, ordered: bool = False)[source]¶
class Meta options for the
Schema
. Defines defaults.
- exception marshmallow.ValidationError(message: str | list | dict, field_name: str = '_schema', data: Mapping[str, Any] | Iterable[Mapping[str, Any]] | None = None, valid_data: list[dict[str, Any]] | dict[str, Any] | None = None, **kwargs)[source]¶
Raised when validation fails on a field or schema.
Validators and custom fields should raise this exception.
- Parameters:
message – 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 – Field name to store the error on. If
None
, the error is stored as schema-level error.data – Raw input data.
valid_data – Valid (de)serialized data.
- marshmallow.post_dump(fn: Callable[[...], Any] | None = None, pass_many: bool = False, pass_original: bool = False) Callable[[...], Any] [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
many
argument 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:
many
is always passed as a keyword arguments to the decorated method.
- marshmallow.post_load(fn: Callable[[...], Any] | None = None, pass_many: bool = False, pass_original: bool = False) Callable[[...], Any] [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
many
argument 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:
partial
andmany
are always passed as keyword arguments to the decorated method.
- marshmallow.pprint(obj, *args, **kwargs) None [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.
- marshmallow.pre_dump(fn: Callable[[...], Any] | None = None, pass_many: bool = False) Callable[[...], Any] [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
many
argument passed to theSchema
’sdump()
call. Ifpass_many=True
, the raw data (which may be a collection) is passed.Changed in version 3.0.0:
many
is always passed as a keyword arguments to the decorated method.
- marshmallow.pre_load(fn: Callable[[...], Any] | None = None, pass_many: bool = False) Callable[[...], Any] [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
many
argument passed to theSchema
’sload()
call. Ifpass_many=True
, the raw data (which may be a collection) is passed.Changed in version 3.0.0:
partial
andmany
are always passed as keyword arguments to the decorated method.
- marshmallow.validates(field_name: str) Callable[[...], Any] [source]¶
Register a field validator.
- Parameters:
field_name (str) – Name of the field that the method validates.
- marshmallow.validates_schema(fn: Callable[[...], Any] | None = None, pass_many: bool = False, pass_original: bool = False, skip_on_field_errors: bool = True) Callable[[...], Any] [source]¶
Register a schema-level validator.
By default it receives a single object at a time, transparently handling the
many
argument 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_errors
defaults toTrue
.Changed in version 3.0.0:
partial
andmany
are always passed as keyword arguments to the decorated method.
- marshmallow.EXCLUDE¶
- marshmallow.INCLUDE¶
- marshmallow.RAISE¶
- marshmallow.missing¶