0
# Field Types
1
2
Marshmallow provides comprehensive field types for handling data conversion, validation, and transformation during serialization and deserialization. Each field type is specialized for specific data formats and use cases.
3
4
## Capabilities
5
6
### Base Field Class
7
8
All field types inherit from the base Field class, which provides common functionality and configuration options.
9
10
```python { .api }
11
class Field:
12
def __init__(self, *, dump_default=missing, load_default=missing, data_key=None,
13
attribute=None, validate=None, required=False, allow_none=None,
14
load_only=False, dump_only=False, error_messages=None, metadata=None):
15
"""
16
Base field class for all field types.
17
18
Parameters:
19
- dump_default: default value when serializing if attribute is missing
20
- load_default: default value when deserializing if key is missing
21
- data_key: key name in serialized data (different from attribute name)
22
- attribute: attribute name on the object (different from field name)
23
- validate: validator or list of validators to apply
24
- required: bool, whether field is required during deserialization
25
- allow_none: bool, whether None values are allowed
26
- load_only: bool, skip field during serialization
27
- dump_only: bool, skip field during deserialization
28
- error_messages: dict, custom error message overrides
29
- metadata: dict, additional metadata for the field
30
"""
31
32
class Raw(Field):
33
"""
34
Field that applies no formatting - outputs values as-is.
35
"""
36
```
37
38
### String and Text Fields
39
40
Fields for handling text data with various validation and formatting options.
41
42
```python { .api }
43
class String(Field):
44
"""
45
String field for text data.
46
47
Parameters:
48
- allow_empty: bool, whether to allow empty strings (default: True)
49
"""
50
51
# Alias for String
52
Str = String
53
54
class Email(Field):
55
"""
56
Email address field with built-in email validation.
57
"""
58
59
class URL(Field):
60
"""
61
URL field with validation.
62
63
Parameters:
64
- relative: bool, allow relative URLs (default: False)
65
- schemes: set, valid URL schemes (default: http, https, ftp, ftps)
66
- require_tld: bool, require top-level domain (default: True)
67
"""
68
69
# Alias for URL
70
Url = URL
71
72
class UUID(Field):
73
"""
74
UUID field that serializes to string and deserializes to uuid.UUID objects.
75
"""
76
```
77
78
### Numeric Fields
79
80
Fields for handling various numeric data types with validation and precision control.
81
82
```python { .api }
83
class Number(Field):
84
"""
85
Base class for numeric fields.
86
"""
87
88
class Integer(Field):
89
"""
90
Integer field.
91
92
Parameters:
93
- strict: bool, whether to disallow non-integer numeric types (default: False)
94
"""
95
96
# Alias for Integer
97
Int = Integer
98
99
class Float(Field):
100
"""
101
Floating point number field.
102
103
Parameters:
104
- allow_nan: bool, whether to allow NaN values (default: True)
105
"""
106
107
class Decimal(Field):
108
"""
109
Decimal field using decimal.Decimal for precise decimal arithmetic.
110
111
Parameters:
112
- places: int, number of decimal places for quantization
113
- rounding: decimal rounding mode (ROUND_HALF_EVEN, etc.)
114
- allow_nan: bool, whether to allow NaN values (default: True)
115
"""
116
```
117
118
### Boolean Fields
119
120
Fields for handling boolean values with flexible truth/falsy value mapping.
121
122
```python { .api }
123
class Boolean(Field):
124
"""
125
Boolean field with configurable truthy/falsy values.
126
127
Parameters:
128
- truthy: set, values that evaluate to True (default: {True, 1, '1', 'true', 'True'})
129
- falsy: set, values that evaluate to False (default: {False, 0, '0', 'false', 'False'})
130
"""
131
132
# Alias for Boolean
133
Bool = Boolean
134
```
135
136
### Date and Time Fields
137
138
Fields for handling various date and time formats with flexible serialization options.
139
140
```python { .api }
141
class DateTime(Field):
142
"""
143
DateTime field for datetime objects.
144
145
Parameters:
146
- format: str, datetime format string, 'timestamp', 'iso8601', or None for ISO format
147
"""
148
149
class NaiveDateTime(Field):
150
"""
151
Naive datetime field that requires timezone-naive datetime objects.
152
"""
153
154
class AwareDateTime(Field):
155
"""
156
Timezone-aware datetime field that requires timezone-aware datetime objects.
157
"""
158
159
class Date(Field):
160
"""
161
Date field for date objects.
162
163
Parameters:
164
- format: str, date format string or None for ISO format
165
"""
166
167
class Time(Field):
168
"""
169
Time field for time objects.
170
171
Parameters:
172
- format: str, time format string or None for ISO format
173
"""
174
175
class TimeDelta(Field):
176
"""
177
TimeDelta field for duration values.
178
179
Parameters:
180
- precision: str, serialization precision ('days', 'seconds', 'microseconds', 'milliseconds')
181
"""
182
```
183
184
### Container Fields
185
186
Fields for handling collections and nested data structures.
187
188
```python { .api }
189
class List(Field):
190
"""
191
List field containing items of a specific type.
192
193
Parameters:
194
- inner: Field instance, field type for list items
195
"""
196
197
class Tuple(Field):
198
"""
199
Tuple field with items of specific types.
200
201
Parameters:
202
- tuple_fields: sequence, field types for each tuple position
203
"""
204
205
class Dict(Field):
206
"""
207
Dictionary field with optional key/value type validation.
208
209
Parameters:
210
- keys: Field instance, field type for dictionary keys
211
- values: Field instance, field type for dictionary values
212
"""
213
214
class Mapping(Field):
215
"""
216
Generic mapping field (base class for Dict).
217
"""
218
```
219
220
### Relationship Fields
221
222
Fields for handling relationships between objects and nested schemas.
223
224
```python { .api }
225
class Nested(Field):
226
"""
227
Field for nesting schemas within schemas.
228
229
Parameters:
230
- schema: Schema class or instance for nested object
231
- many: bool, whether this field represents a collection
232
- unknown: str, how to handle unknown fields in nested schema
233
"""
234
235
class Pluck(Field):
236
"""
237
Field that plucks a single value from a nested object.
238
239
Parameters:
240
- schema: Schema class for the nested object
241
- field_name: str, name of field to pluck from nested object
242
"""
243
```
244
245
### IP Address Fields
246
247
Fields for handling various IP address formats with validation.
248
249
```python { .api }
250
class IP(Field):
251
"""
252
IPv4 or IPv6 address field that accepts both formats.
253
"""
254
255
class IPv4(Field):
256
"""
257
IPv4 address field with validation.
258
"""
259
260
class IPv6(Field):
261
"""
262
IPv6 address field with validation.
263
"""
264
265
class IPv4Interface(Field):
266
"""
267
IPv4 network interface field (IP address with subnet).
268
"""
269
270
# Alias for IPv4Interface
271
IPInterface = IPv4Interface
272
273
class IPv6Interface(Field):
274
"""
275
IPv6 network interface field (IP address with subnet).
276
"""
277
```
278
279
### Special Purpose Fields
280
281
Fields for specialized use cases and dynamic value generation.
282
283
```python { .api }
284
class Enum(Field):
285
"""
286
Field for Python enum values.
287
288
Parameters:
289
- enum: Enum class to validate against
290
- by_value: bool, whether to serialize by value (True) or by name (False)
291
"""
292
293
class Method(Field):
294
"""
295
Field that gets its value from a schema method.
296
297
Parameters:
298
- serialize: str, method name to call for serialization
299
- deserialize: str, method name to call for deserialization
300
"""
301
302
class Function(Field):
303
"""
304
Field that gets its value from a function.
305
306
Parameters:
307
- serialize: callable, function to call for serialization
308
- deserialize: callable, function to call for deserialization
309
"""
310
311
class Constant(Field):
312
"""
313
Field that always serializes to the same constant value.
314
315
Parameters:
316
- constant: the constant value to serialize
317
"""
318
```
319
320
## Usage Examples
321
322
### Basic Field Usage
323
324
```python
325
from marshmallow import Schema, fields
326
327
class PersonSchema(Schema):
328
name = fields.Str(required=True)
329
age = fields.Int(validate=lambda x: x >= 0)
330
email = fields.Email()
331
website = fields.URL(schemes=['http', 'https'])
332
uuid = fields.UUID()
333
active = fields.Bool()
334
```
335
336
### Date and Time Fields
337
338
```python
339
class EventSchema(Schema):
340
name = fields.Str()
341
start_date = fields.Date()
342
start_time = fields.DateTime(format='%Y-%m-%d %H:%M:%S')
343
duration = fields.TimeDelta(precision='seconds')
344
created_at = fields.DateTime(format='timestamp') # Unix timestamp
345
```
346
347
### Container Fields
348
349
```python
350
class ArticleSchema(Schema):
351
title = fields.Str()
352
tags = fields.List(fields.Str()) # List of strings
353
metadata = fields.Dict(keys=fields.Str(), values=fields.Raw()) # String keys, any values
354
coordinates = fields.Tuple([fields.Float(), fields.Float()]) # Lat/lon pair
355
```
356
357
### Nested Relationships
358
359
```python
360
class AuthorSchema(Schema):
361
name = fields.Str()
362
email = fields.Email()
363
364
class BookSchema(Schema):
365
title = fields.Str()
366
author = fields.Nested(AuthorSchema)
367
authors = fields.Nested(AuthorSchema, many=True) # Multiple authors
368
primary_author_name = fields.Pluck(AuthorSchema, 'name') # Just the name
369
```
370
371
### Advanced Field Configuration
372
373
```python
374
class UserSchema(Schema):
375
# Custom data key mapping
376
user_id = fields.Int(data_key='id')
377
378
# Default values
379
status = fields.Str(dump_default='active')
380
join_date = fields.DateTime(load_default=lambda: datetime.now())
381
382
# Load/dump only fields
383
password = fields.Str(load_only=True)
384
full_name = fields.Method('get_full_name', dump_only=True)
385
386
# Custom validation
387
username = fields.Str(validate=[Length(min=3, max=20), Regexp(r'^[a-zA-Z0-9_]+$')])
388
389
def get_full_name(self, obj):
390
return f"{obj.first_name} {obj.last_name}"
391
```