API

api.api(title, version, dev_username, dev_password)[source]

Error Handler

class api.error_handler.Base_Handler[source]
class api.error_handler.Bad_Request_Handler[source]
error

alias of falcon.errors.HTTPBadRequest

class api.error_handler.Internal_Server_Error_Handler[source]
error

alias of falcon.errors.HTTPInternalServerError

class api.error_handler.Unsupported_Media_Type_Handler[source]
error

alias of falcon.errors.HTTPUnsupportedMediaType

Media Handler

class api.media_handler.XML_Handler(dumps=None, loads=None)[source]
deserialize(stream, content_type, content_length)[source]

Deserialize the falcon.Request body.

Args:

stream (object): Input data to deserialize. content_type (str): Type of request content. content_length (int): Length of request content.

Returns:

object: A deserialized object.

class api.media_handler.YAML_Handler(dumps=None, loads=None)[source]
deserialize(stream, content_type, content_length)[source]

Deserialize the falcon.Request body.

Args:

stream (object): Input data to deserialize. content_type (str): Type of request content. content_length (int): Length of request content.

Returns:

object: A deserialized object.

Middleware

class api.middleware.Basic_Auth_Backend_Middleware(dev_username, dev_password)[source]
authenticate(req, resp, resource)[source]

Extract basic auth token from request authorization header, deocode the token, verifies the username/password and return either a user object if successful else raise an falcon.HTTPUnauthoried exception

get_auth_header(user_payload)

Returns the value for authorization header Args:

user_payload(dict, required): A dict containing required information

to create authentication token

get_auth_token(user_payload)

Extracts username, password from the user_payload and encode the credentials username:password in base64 form

parse_auth_token_from_request(auth_header)

Parses and returns Auth token from the request header. Raises falcon.HTTPUnauthoried exception with proper error message

class api.middleware.Negotiation_Middleware[source]

Spec

class api.spec.Spec(api, title, version)[source]

Docstring

@docstring.docstring[source]

Generate automatic docstring for the class with a decorator.

Returns

decorator

Lib

class lib.http.HTTP_Method[source]

Constants representing various HTTP request methods.

lib.http.HTTP_Status

alias of http.HTTPStatus

class lib.polycube.Polycube[source]

Response

class lib.response.Base_Response(message, error=False, exception=None, **kwargs)[source]
class lib.response.Bad_Request_Response(exception=None, **kwargs)[source]
class lib.response.Conflict_Response(message, exception=None, **kwargs)[source]
class lib.response.Content_Response(content)[source]
class lib.response.Created_Response(message, **kwargs)[source]
class lib.response.Internal_Server_Error_Response(message, **kwargs)[source]
class lib.response.No_Content_Response(message, exception=None, **kwargs)[source]
class lib.response.Not_Acceptable_Response(message, exception=None, **kwargs)[source]
class lib.response.Not_Found_Response(message, exception=None, **kwargs)[source]
class lib.response.Not_Modified_Response(message, **kwargs)[source]
class lib.response.Ok_Response(message, **kwargs)[source]
class lib.response.Reset_Content_Response(message, **kwargs)[source]
class lib.response.Unauthorized_Response[source]
class lib.response.Unprocessable_Entity_Response(message, exception=None, **kwargs)[source]
class lib.response.Unsupported_Media_Type_Response(exception=None, **kwargs)[source]

Reader

class reader.arg.Arg_Reader[source]
class reader.config.Config_Reader[source]
class Env_Interpolation[source]

Interpolation which expands environment variables in values.

_interpolate_some(parser, option, accum, rest, section, map, depth)
before_get(parser, section, option, value, defaults)[source]

Executes before getting the value.

Parameters
  • self – class instance

  • parser – configparser instance

  • section – section value

  • option – option value

  • value – current value

  • defaults – default values

Returns

value with expanded variables

before_read(parser, section, option, value)
before_set(parser, section, option, value)
before_write(parser, section, option, value)

Resource

resource.routes(api, spec)[source]
class resource.base.Base_Resource[source]
class resource.code.Code_Resource[source]
on_delete(req, resp, id=None)[source]

Inject code at run-time in the local environment. — summary: Code injection description: Inject code at run-time in the local environment. parameters:

  • name: payload required: true in: body schema:

    type: array items: Code_Request_Schema

tags: [code] responses:

200:

description: Codes inject correctly. schema:

oneOf:
  • type: array items: Created_Response

204:

description: No content to inject codes based on the request. schema: No_Content_Response_Schema

400:

description: Request not valid. schema: Bad_Request_Response_Schema

401:

description: Authentication failed. schema: Unauthorized_Response_Schema

406:

description: Request validation failed. schema: Not_Acceptable_Response_Schema

422:

description: Not possible to inject one or more codes. schema:

type: array items:

oneOf:
  • Created_Response_Schema

  • Unprocessable_Entity_Response_Schema

500:

description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema

on_post(req, resp, id=None)[source]

Inject code at run-time in the local environment. — summary: Code injection description: Inject code at run-time in the local environment. parameters:

  • name: payload required: true in: body schema:

    type: array items: Code_Request_Schema

tags: [code] responses:

200:

description: Codes inject correctly. schema:

oneOf:
  • type: array items: Created_Response

204:

description: No content to inject codes based on the request. schema: No_Content_Response_Schema

400:

description: Request not valid. schema: Bad_Request_Response_Schema

401:

description: Authentication failed. schema: Unauthorized_Response_Schema

406:

description: Request validation failed. schema: Not_Acceptable_Response_Schema

422:

description: Not possible to inject one or more codes. schema:

type: array items:

oneOf:
  • Created_Response_Schema

  • Unprocessable_Entity_Response_Schema

500:

description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema

on_put(req, resp, id=None)[source]

Update the injected code at run-time in the local environment. — summary: Update injected code description: Update the injected code at run-time in the local environment. parameters:

  • name: payload required: true in: body schema:

    type: array items: Code_Request_Schema

tags: [code] responses:

200:

description: All injected code correctly updated. schema:

type: array items: Ok_Response_Schema

204:

description: No content to update codes based on the request. schema: No_Content_Response_Schema

304:

description: Update for one or more codes not necessary. schema:

type: array items:

oneOf:
  • Ok_Response_Schema

  • Not_Modified_Response

400:

description: Request not valid. schema: Bad_Request_Response_Schema

401:

description: Authentication failed. schema: Unauthorized_Response_Schema

406:

description: Request validation failed. schema: Not_Acceptable_Response_Schema

415:

description: Media type not supported. schema: Unsupported_Media_Type_Response_Schema

422:

description: Not possible to update one or more codes based on the request. schema:

type: array items:

oneOf:
  • Ok_Response_Schema

  • Not_Modified_Response

  • Unprocessable_Entity_Response_Schema

500:

description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema

class resource.config.Config_Resource[source]
on_post(req, resp)[source]

Apply configuration changes to the local environment. — summary: Configuration update description: Apply configuration changes to the local environment. tags: [config] parameters:

  • name: payload required: true in: body schema:

    type: array items: Config_Request_Schema

responses:
200:

description: Configuration changed correctly. schema:

oneOf:
  • type: array items: Created_Response

204:

description: No content to configure based on the request. schema: No_Content_Response_Schema

400:

description: Request not valid. schema: Bad_Request_Response_Schema

401:

description: Authentication failed. schema: Unauthorized_Response_Schema

406:

description: Request validation failed. schema: Not_Acceptable_Response_Schema

422:

description: Not possible to change one or more configurations. schema:

type: array items:

oneOf:
  • Created_Response_Schema

  • Unprocessable_Entity_Response_Schema

500:

description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema

class resource.status.Status_Resource[source]
on_get(req, resp)[source]

Get info about the status of the LCP in the execution environment. — summary: Status info description: Get info about the status of the LCP in the execution environment. tags: [status] responses:

200:

description: Status data of the LCP. schema: Status_Response_Schema

400:

description: Request not valid. schema: Bad_Request_Response_Schema

401:

description: Authentication failed. schema: Unauthorized_Response_Schema

406:

description: Request validation failed. schema: Not_Acceptable_Response_Schema

500:

description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema

on_post(req, resp)[source]

Set the last heartbeat. — summary: Status set. description: Set the last heartbeat. tags: [status] responses:

200:

description: Heartbeat with CB-Manager correctly executed. schema: Status_Response_Schema

400:

description: Request not valid. schema: Bad_Request_Response_Schema

401:

description: Authentication failed. schema: Unauthorized_Response_Schema

406:

description: Request validation failed. schema: Not_Acceptable_Response_Schema

500:

description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema

Schema

class schema.validate.In[source]
class schema.validate.Unique_List[source]
class schema.base.Base_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)[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. If None, the value for self.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.

New in version 1.1.0.

Code

class schema.code.Code_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Request for code endpoint.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

Config

Request

class schema.config.Config_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Request for config endpoint.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

class schema.config.Config_Action_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Action part in a single item of the code request.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

class schema.config.Config_Parameter_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Parameter part in a single item of the code request.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

class schema.config.Config_Resource_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Resource part in a single item of the code request.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

Response

class schema.config.Config_Action_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Action part in a single item of the config response.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

class schema.config.Config_Parameter_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Parameter part in a single item of the config response.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

class schema.config.Config_Parameter_Value_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Parameter value part in a single item of the config response.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

class schema.config.Config_Resource_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Resource part in a single item of the config response.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

Status

class schema.status.Status_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Response for status endpoint.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

class schema.status.Status_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]

Response for status endpoint.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)

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. If None, the value for self.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.

New in version 1.1.0.

Response

class schema.response.Exception_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Base_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]

Response for the item creation.

class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Bad_Request_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Conflict_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Content_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Created_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.No_Content_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Not_Acceptable_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Not_Found_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Not_Modified_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Ok_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Reset_Content_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Unauthorized_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Unprocessable_Entity_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

class schema.response.Unsupported_Media_Type_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]
class Meta

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 the

    explicitly declared fields. additional and fields are mutually-exclusive options.

  • include: 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. May be an OrderedDict.

  • exclude: Tuple or list of fields to exclude in the serialized result.

    Nested fields can be represented with dot delimiters.

  • dateformat: Default format for Date <fields.Date> fields.

  • datetimeformat: Default format for DateTime <fields.DateTime> fields.

  • timeformat: Default format for Time <fields.Time> fields.

  • render_module: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.

    Defaults to json from the standard library.

  • ordered: If True, order serialization output according to the

    order in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.

  • index_errors: If True, errors dictionaries will include the index

    of 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

  • unknown: Whether to exclude, include, or raise an error for unknown

    fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • register: Whether to register the Schema with marshmallow’s internal

    class registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.

OPTIONS_CLASS

alias of marshmallow.schema.SchemaOpts

_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).

Also set field load_only and dump_only values if field_name was specified in class Meta.

static _call_and_store(getter_func, data, *, field_name, error_store, index=None)

Call getter_func with data as its argument, and store any ValidationErrors.

Parameters
  • getter_func (callable) – Function for getting the serialized/deserialized value from data.

  • data – The data passed to getter_func.

  • field_name (str) – Field name.

  • index (int) – Index of the item being validated, if validating a collection, otherwise None.

_deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None)Union[_T, List[_T]]

Deserialize data.

Parameters
  • data (dict) – The data to deserialize.

  • error_store (ErrorStore) – Structure to store errors.

  • many (bool) – True if data should be deserialized as a collection.

  • partial (bool|tuple) – 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 or RAISE.

  • index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.

Returns

A dictionary of the deserialized data.

_do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)

Deserialize data, returning the deserialized result. This method is private API.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

  • postprocess – Whether to run post_load methods..

Returns

Deserialized data

_init_fields()None

Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.

_normalize_nested_options()None

Apply then flatten nested schema options. This method is private API.

_serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)

Serialize obj.

Parameters
  • obj – The object(s) to serialize.

  • many (bool) – True if data should be serialized as a collection.

Returns

A dictionary of the serialized data

Changed in version 1.0.0: Renamed from marshal.

dump(obj: Any, *, many: Optional[bool] = None)

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. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A json string

Return type

str

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

fields

Dictionary mapping field_names -> Field objects

classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema')type

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
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

New in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

New in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)

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.

New in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)

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. If None, the value for self.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 or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

New in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: marshmallow.fields.Field)None

Hook to modify a field when it is bound to the Schema.

No-op by default.

validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None)Dict[str, List[str]]

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. If None, the value for self.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.

New in version 1.1.0.

Utils

Datetime

utils.datetime.FORMAT = '%Y/%m/%dT%H:%M:%S'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

utils.datetime.datetime_from_str(date_time_str, format='%Y/%m/%dT%H:%M:%S')[source]

Get a datetime object from the string.

Params date_time_str

datetime in string

Params format

datetime format

Returns

datetime object

utils.datetime.datetime_to_str(date_time=None, format='%Y/%m/%dT%H:%M:%S')[source]

Convert the datetime to string in the given format.

Params data_time

datetime input

Params format

datetime format

Returns

datetime string in the given format

Exception

utils.exception.extract_info(exception)[source]
utils.exception.to_str(exception)[source]

Hash

utils.hash.hash(text)[source]

Make a hash of the text

Parameters

text – text to make the hash

Returns

hashed version of the text

utils.hash.generate_username()[source]

Generate a new password.

Returns

new username

utils.hash.generate_password()[source]

Generate a random password.

Returns

random password

JSON

utils.json.dumps(data, *args, **kwargs)[source]
utils.json.loads(data, *args, **kwargs)[source]

Log

class utils.log.Log[source]

Wrapper class for coloured and verbuse logs.

classmethod get(name)[source]

Return the initialized logger with the module name.

Parameters
  • cls – Log class.

  • name – module name

Returns

logger instance

static get_levels()[source]

Get list of log level names.

Returns

list of string

classmethod init(default, levels)[source]

Set the default and levels and initialize the log manager. :param cls: Log class. :param default: default log level :param levels: log levels

Sequence

utils.sequence.expand(elements, **kwrds)[source]
utils.sequence.format(elements, data)[source]
utils.sequence.is_dict(obj)[source]
utils.sequence.is_list(obj)[source]
utils.sequence.iterate(source, *keys)[source]

Iterate a nested dict based on list of keys.

Parameters
  • source – nested dict

  • keys – list of keys

Returns

value

utils.sequence.subset(elements, *keys, negation=False)[source]
utils.sequence.table_to_dict(data)[source]
utils.sequence.wrap(data)[source]

Wrap the data if an array if it is ont a list of tuple.

Parameters

data – data to wrap

Returns

wrapped data

Signal

utils.signal.send_tree(pid, sig=<Signals.SIGTERM: 15>, include_parent=True, timeout=None, on_terminate=None)[source]

Kill a process tree (including grandchildren) with signal “sig” and return a (gone, still_alive) tuple. “on_terminate”, if specified, is a callback function which is called as soon as a child terminates.

String

class utils.string.Formatter[source]
utils.string.is_str(obj)[source]
utils.string.format = <bound method Formatter.format of <utils.string.Formatter object>>

Time

utils.time.get_seconds(text, to_int=False)[source]

Parse the text to get the equivalent number of seconds (e.g., 1min => 60).

Params text

input time in human format, e.g.: 1m

Params to_int

convert to int the result

Returns

number of seconds