PydanticSchema¶
The main schema class that bridges Pydantic and Marshmallow.
Classes¶
PydanticSchema
¶
PydanticSchema(
*,
only: Sequence[str] | None = None,
exclude: Sequence[str] = (),
context: dict[str, Any] | None = None,
load_only: Sequence[str] = (),
dump_only: Sequence[str] = (),
partial: bool | Sequence[str] | Set[str] | None = None,
unknown: str | None = None,
many: bool | None = None,
**kwargs: Any,
)
Bases: _PydanticSchema[M], Generic[M]
Factory Functions¶
schema_for
¶
Shortcut to create a Marshmallow schema from a Pydantic model.
Example
from pydantic import BaseModel, EmailStr
class User(BaseModel): name: str email: EmailStr
UserSchema = schema_for(User)
Use it¶
schema = UserSchema() user = schema.load({"name": "Alice", "email": "alice@example.com"}) print(user.name) # "Alice" - it's a User instance!
pydantic_schema
¶
Decorator that adds a .Schema attribute to a Pydantic model.
This is the simplest way to use pydantic-marshmallow. Just decorate
your Pydantic model and use .Schema anywhere Marshmallow is expected.
Example
from pydantic import BaseModel, EmailStr from pydantic_marshmallow import pydantic_schema
@pydantic_schema class User(BaseModel): name: str email: EmailStr
Use .Schema anywhere Marshmallow schemas are expected:¶
schema = User.Schema() user = schema.load({"name": "Alice", "email": "alice@example.com"})
user is a User instance!¶
Works with webargs:¶
@use_args(User.Schema(), location="json") def create_user(user): ...
Works with apispec:¶
spec.components.schema("User", schema=User.Schema)
All Marshmallow hooks still work:¶
class UserSchema(User.Schema): @pre_load def normalize(self, data, **kwargs): data["email"] = data["email"].lower() return data