API Reference

Marshmallow

Schema-based serialization and validation library converting complex Python types to and from plain data.

Official Documentation ↗
CompatibilityThis documentation covers version v3. Check the official docs for the latest API surface.

Installation

pippip install marshmallow

Methods

Schema-based serialization and validation library converting complex Python types to and from plain data.

Overview

Marshmallow schemas describe the shape of data both ways: load validates and deserializes input, dump serializes objects back out. Fields carry types, constraints, and defaults, and ValidationError aggregates every problem with per-field messages.

Hooks, pre_load, post_load, and their dump counterparts, adapt between wire formats and domain objects, while Nested composes schemas into documents. The library stays independent of web frameworks and ORMs, which makes it a common boundary layer between them.

Core Methods

The most frequently used entry points, with signatures and runnable examples:

  • Schema — Declares fields with types, required flags, and validators describing the accepted data shape.
  • schema.load — Validates and deserializes input into a dict, collecting field-level errors in ValidationError.
  • schema.dump — Serializes objects to plain dicts or JSON strings, applying only and exclude field rules.
  • @post_load — Hook converting the validated dict into a domain object at the end of load.

Usage Notes

  • Instantiate schemas once and reuse them; compilation and field binding are not free.
  • Return err.messages to clients as-is: the per-field structure maps directly onto form errors.
  • Use unknown=“exclude” at edges where extra client keys are noise rather than an attack.

Common Pitfalls

  • load returns dicts unless a post_load hook constructs objects; assuming instances breaks downstream code.
  • Raising inside validators loses the aggregated error shape; prefer validate callables and let marshmallow collect.
  • Forgetting required=True turns silent None fields into downstream TypeErrors far from the boundary.

FAQ

How does marshmallow differ from pydantic?
Pydantic validates through type annotations and builds instances directly. Marshmallow uses explicit field declarations and centers on serialization round-trips, which suits object-relational boundaries where you dump ORM models and load external payloads.
Where do nested structures fit?
fields.Nested(OtherSchema) validates sub-objects recursively, and fields.List(items=fields.Nested(...)) handles collections. Errors preserve the nesting shape, so clients can map messages to form fields.
What does dump_only protect?
dump_only fields are emitted on serialization but rejected on load, modeling server-controlled values such as ids and timestamps so clients cannot supply them.