0
# Schema Definition
1
2
Schema classes define the structure and rules for serializing Python objects to JSON-compatible data and deserializing input data back to Python objects. Schemas provide comprehensive control over field mapping, validation, data transformation, and error handling.
3
4
## Capabilities
5
6
### Schema Class
7
8
The base Schema class provides core serialization and deserialization functionality with extensive configuration options.
9
10
```python { .api }
11
class Schema:
12
def __init__(self, *, only=None, exclude=(), many=None, load_only=(),
13
dump_only=(), partial=None, unknown=None):
14
"""
15
Initialize a Schema instance.
16
17
Parameters:
18
- only: list/tuple, fields to include (whitelist)
19
- exclude: list/tuple, fields to exclude (blacklist, default: ())
20
- many: bool, whether to serialize/deserialize a collection of objects
21
- load_only: list/tuple, fields only used during deserialization (default: ())
22
- dump_only: list/tuple, fields only used during serialization (default: ())
23
- partial: bool/list, allow partial loading (skip required validation)
24
- unknown: str, how to handle unknown fields (EXCLUDE/INCLUDE/RAISE)
25
"""
26
27
def dump(self, obj, *, many=None):
28
"""
29
Serialize objects to JSON-compatible Python data types.
30
31
Parameters:
32
- obj: object or list of objects to serialize
33
- many: bool, override instance's many setting
34
35
Returns:
36
dict or list of dicts with serialized data
37
"""
38
39
def dumps(self, obj, *, many=None, **kwargs):
40
"""
41
Serialize objects to JSON string.
42
43
Parameters:
44
- obj: object or list of objects to serialize
45
- many: bool, override instance's many setting
46
- **kwargs: additional arguments passed to json.dumps
47
48
Returns:
49
str: JSON string representation
50
"""
51
52
def load(self, json_data, *, many=None, partial=None, unknown=None):
53
"""
54
Deserialize input data to Python objects.
55
56
Parameters:
57
- json_data: dict or list of dicts to deserialize
58
- many: bool, override instance's many setting
59
- partial: bool/list, allow partial loading
60
- unknown: str, how to handle unknown fields
61
62
Returns:
63
dict or list of dicts with deserialized data
64
65
Raises:
66
ValidationError: if validation fails
67
"""
68
69
def loads(self, json_str, *, many=None, partial=None, unknown=None, **kwargs):
70
"""
71
Deserialize JSON string to Python objects.
72
73
Parameters:
74
- json_str: str, JSON string to deserialize
75
- many: bool, override instance's many setting
76
- partial: bool/list, allow partial loading
77
- unknown: str, how to handle unknown fields
78
- **kwargs: additional arguments passed to json.loads
79
80
Returns:
81
dict or list of dicts with deserialized data
82
83
Raises:
84
ValidationError: if validation fails
85
"""
86
87
def validate(self, json_data, *, many=None, partial=None, unknown=None):
88
"""
89
Validate input data without deserializing.
90
91
Parameters:
92
- json_data: dict or list of dicts to validate
93
- many: bool, override instance's many setting
94
- partial: bool/list, allow partial validation
95
- unknown: str, how to handle unknown fields
96
97
Returns:
98
dict: validation errors (empty dict if valid)
99
"""
100
101
class Meta:
102
"""
103
Schema configuration class.
104
105
Attributes:
106
- fields: tuple, field names to include
107
- exclude: tuple, field names to exclude
108
- load_only: tuple, fields only used during deserialization
109
- dump_only: tuple, fields only used during serialization
110
- unknown: str, how to handle unknown fields (EXCLUDE/INCLUDE/RAISE)
111
- include: dict, additional fields to include
112
- dateformat: str, default date format
113
- datetimeformat: str, default datetime format
114
- timeformat: str, default time format
115
- render_module: module, JSON serialization module (default: json)
116
- ordered: bool, whether to preserve field order
117
- register: bool, whether to register schema in class registry
118
"""
119
```
120
121
### Schema Configuration Options
122
123
The SchemaOpts class handles schema configuration and Meta class processing.
124
125
```python { .api }
126
class SchemaOpts:
127
def __init__(self, meta, ordered=False):
128
"""
129
Initialize schema options from Meta class.
130
131
Parameters:
132
- meta: Meta class with configuration attributes
133
- ordered: bool, whether to preserve field order
134
"""
135
```
136
137
### Schema Metaclass
138
139
The SchemaMeta metaclass processes Schema class definitions and manages field declaration.
140
141
```python { .api }
142
class SchemaMeta(type):
143
def __new__(cls, name, bases, namespace, **kwargs):
144
"""
145
Create a new Schema class with processed field definitions.
146
"""
147
148
@classmethod
149
def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_fields):
150
"""
151
Get all declared fields for a schema class.
152
153
Parameters:
154
- klass: Schema class being created
155
- cls_fields: fields declared directly on the class
156
- inherited_fields: fields inherited from parent classes
157
- dict_fields: fields from Meta.fields
158
159
Returns:
160
dict: mapping of field names to Field instances
161
"""
162
```
163
164
## Usage Examples
165
166
### Basic Schema Definition
167
168
```python
169
from marshmallow import Schema, fields
170
171
class UserSchema(Schema):
172
id = fields.Int()
173
username = fields.Str(required=True)
174
email = fields.Email(required=True)
175
created_at = fields.DateTime(dump_only=True)
176
password = fields.Str(load_only=True)
177
178
# Usage
179
schema = UserSchema()
180
user_data = {"id": 1, "username": "john", "email": "john@example.com"}
181
result = schema.dump(user_data)
182
```
183
184
### Schema with Meta Configuration
185
186
```python
187
class ProductSchema(Schema):
188
name = fields.Str()
189
price = fields.Decimal()
190
description = fields.Str()
191
internal_id = fields.Int()
192
193
class Meta:
194
# Only include specific fields
195
fields = ("name", "price", "description")
196
# Set default datetime format
197
datetimeformat = "%Y-%m-%d %H:%M:%S"
198
# Handle unknown fields by including them
199
unknown = INCLUDE
200
```
201
202
### Dynamic Schema Creation
203
204
```python
205
# Create schema with runtime field selection
206
schema = UserSchema(only=("username", "email"))
207
result = schema.dump(user)
208
209
# Exclude sensitive fields
210
schema = UserSchema(exclude=("password", "internal_id"))
211
result = schema.dump(user)
212
213
# Handle collections
214
users_data = [user1, user2, user3]
215
schema = UserSchema(many=True)
216
result = schema.dump(users_data)
217
```
218
219
### Partial Loading
220
221
```python
222
# Allow partial updates (skip required field validation)
223
schema = UserSchema()
224
partial_data = {"username": "new_username"}
225
result = schema.load(partial_data, partial=True)
226
227
# Partial loading for specific fields only
228
result = schema.load(partial_data, partial=("username", "email"))
229
```