or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

error-handling.mdindex.mdjson-processing.mdschema-building.mdspecial-values.mdurl-network.mdvalidation-serialization.md

validation-serialization.mddocs/

0

# Validation and Serialization

1

2

Core classes for validating data against schemas and serializing validated data to various output formats. These are the main classes that most users will interact with when using pydantic-core directly.

3

4

## Capabilities

5

6

### SchemaValidator

7

8

The primary validation class that validates Python data, JSON data, or string data against defined schemas. It provides fast validation with detailed error reporting.

9

10

```python { .api }

11

class SchemaValidator:

12

def __init__(self, schema: CoreSchema, config: CoreConfig = None):

13

"""

14

Create a new schema validator.

15

16

Args:

17

schema: The validation schema to use

18

config: Optional configuration for validation behavior

19

"""

20

21

def validate_python(self, value, *, strict=None, from_attributes=None, context=None, self_instance=None, allow_partial=False, by_alias=None, by_name=None):

22

"""

23

Validate a Python object against the schema.

24

25

Args:

26

value: The Python object to validate

27

strict: Whether to use strict validation (overrides config)

28

from_attributes: Whether to extract values from object attributes

29

context: Additional context for validation

30

self_instance: An instance of a model to set attributes on from validation

31

allow_partial: Whether to allow partial validation (bool or 'off'/'on'/'trailing-strings')

32

by_alias: Whether to use field aliases when validating

33

by_name: Whether to use field names when validating

34

35

Returns:

36

The validated and potentially transformed value

37

38

Raises:

39

ValidationError: If validation fails

40

"""

41

42

def isinstance_python(self, value, *, strict=None, from_attributes=None, context=None, self_instance=None, by_alias=None, by_name=None) -> bool:

43

"""

44

Similar to validate_python but returns a boolean instead of raising ValidationError.

45

46

Args:

47

value: The Python object to validate

48

strict: Whether to use strict validation (overrides config)

49

from_attributes: Whether to extract values from object attributes

50

context: Additional context for validation

51

self_instance: An instance of a model to set attributes on from validation

52

by_alias: Whether to use field aliases when validating

53

by_name: Whether to use field names when validating

54

55

Returns:

56

True if validation succeeds, False if validation fails

57

"""

58

59

def validate_json(self, json_data, *, strict=None, context=None, self_instance=None, allow_partial=False, by_alias=None, by_name=None):

60

"""

61

Validate JSON data against the schema.

62

63

Args:

64

json_data: JSON string, bytes, or bytearray to validate

65

strict: Whether to use strict validation (overrides config)

66

context: Additional context for validation

67

self_instance: An instance of a model to set attributes on from validation

68

allow_partial: Whether to allow partial validation (bool or 'off'/'on'/'trailing-strings')

69

by_alias: Whether to use field aliases when validating

70

by_name: Whether to use field names when validating

71

72

Returns:

73

The validated Python object

74

75

Raises:

76

ValidationError: If validation fails

77

"""

78

79

def validate_strings(self, str_data, *, strict=None, context=None, allow_partial=False, by_alias=None, by_name=None):

80

"""

81

Validate string data against the schema.

82

83

Args:

84

str_data: String data to validate

85

strict: Whether to use strict validation (overrides config)

86

context: Additional context for validation

87

allow_partial: Whether to allow partial validation (bool or 'off'/'on'/'trailing-strings')

88

by_alias: Whether to use field aliases when validating

89

by_name: Whether to use field names when validating

90

91

Returns:

92

The validated Python object

93

94

Raises:

95

ValidationError: If validation fails

96

"""

97

98

def validate_assignment(self, obj, field_name, field_value, *, strict=None, from_attributes=None, context=None, by_alias=None, by_name=None):

99

"""

100

Validate an assignment to a field on a model.

101

102

Args:

103

obj: The model instance being assigned to

104

field_name: The name of the field to validate assignment for

105

field_value: The value to assign to the field

106

strict: Whether to use strict validation (overrides config)

107

from_attributes: Whether to extract values from object attributes

108

context: Additional context for validation

109

by_alias: Whether to use field aliases when validating

110

by_name: Whether to use field names when validating

111

112

Returns:

113

Either the model dict or a tuple of (model_data, model_extra, fields_set)

114

115

Raises:

116

ValidationError: If validation fails

117

"""

118

119

def get_default_value(self, *, strict=None, context=None):

120

"""

121

Get the default value for the schema, including running default value validation.

122

123

Args:

124

strict: Whether to validate the default value in strict mode

125

context: Additional context for validation

126

127

Returns:

128

None if the schema has no default value, otherwise a Some containing the default

129

130

Raises:

131

ValidationError: If validation fails

132

"""

133

134

@property

135

def title(self) -> str:

136

"""The title of the schema."""

137

```

138

139

### SchemaSerializer

140

141

The primary serialization class that converts validated data to various output formats including Python dictionaries, JSON, and custom formats.

142

143

```python { .api }

144

class SchemaSerializer:

145

def __init__(self, schema: CoreSchema, config: CoreConfig = None):

146

"""

147

Create a new schema serializer.

148

149

Args:

150

schema: The serialization schema to use

151

config: Optional configuration for serialization behavior

152

"""

153

154

def to_python(self, value, *, mode=None, include=None, exclude=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, context=None):

155

"""

156

Serialize to Python objects (dicts, lists, etc.).

157

158

Args:

159

value: The value to serialize

160

mode: Serialization mode ('python' or 'json'), defaults to 'python'

161

include: Set of fields to include, if None all fields are included

162

exclude: Set of fields to exclude, if None no fields are excluded

163

by_alias: Whether to use field aliases

164

exclude_unset: Whether to exclude unset fields

165

exclude_defaults: Whether to exclude default values

166

exclude_none: Whether to exclude None values

167

exclude_computed_fields: Whether to exclude computed fields

168

round_trip: Whether to preserve exact types for round-trip compatibility

169

warnings: How to handle invalid fields (bool or 'none'/'warn'/'error')

170

fallback: Fallback function for non-serializable values

171

serialize_as_any: Whether to serialize unknown types as Any

172

context: Additional context for serialization

173

174

Returns:

175

Python objects (dict, list, etc.)

176

"""

177

178

def to_json(self, value, *, indent=None, ensure_ascii=False, include=None, exclude=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, context=None) -> bytes:

179

"""

180

Serialize to JSON bytes.

181

182

Args:

183

value: The value to serialize

184

indent: JSON indentation (None for compact, int for spaces)

185

ensure_ascii: If True, all non-ASCII characters are escaped

186

include: Set of fields to include, if None all fields are included

187

exclude: Set of fields to exclude, if None no fields are excluded

188

by_alias: Whether to use field aliases

189

exclude_unset: Whether to exclude unset fields

190

exclude_defaults: Whether to exclude default values

191

exclude_none: Whether to exclude None values

192

exclude_computed_fields: Whether to exclude computed fields

193

round_trip: Whether to preserve exact types for round-trip compatibility

194

warnings: How to handle invalid fields (bool or 'none'/'warn'/'error')

195

fallback: Fallback function for non-serializable values

196

serialize_as_any: Whether to serialize unknown types as Any

197

context: Additional context for serialization

198

199

Returns:

200

JSON as bytes

201

"""

202

203

@property

204

def serializer(self):

205

"""Access to the underlying serializer implementation."""

206

```

207

208

## Usage Examples

209

210

### Basic Validation

211

212

```python

213

from pydantic_core import SchemaValidator, ValidationError

214

from pydantic_core.core_schema import str_schema, int_schema, dict_schema

215

216

# Create a schema for a person

217

person_schema = dict_schema({

218

'name': str_schema(min_length=1, max_length=100),

219

'age': int_schema(ge=0, le=150),

220

'email': str_schema()

221

})

222

223

# Create validator

224

validator = SchemaValidator(person_schema)

225

226

# Validate valid data

227

valid_person = {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}

228

result = validator.validate_python(valid_person)

229

print(result) # {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}

230

231

# Validate JSON

232

json_data = '{"name": "Bob", "age": 25, "email": "bob@example.com"}'

233

result = validator.validate_json(json_data)

234

print(result) # {'name': 'Bob', 'age': 25, 'email': 'bob@example.com'}

235

```

236

237

### Basic Serialization

238

239

```python

240

from pydantic_core import SchemaSerializer

241

from pydantic_core.core_schema import dict_schema, str_schema, int_schema

242

243

# Create schema and serializer

244

schema = dict_schema({

245

'name': str_schema(),

246

'age': int_schema(),

247

'active': bool_schema()

248

})

249

serializer = SchemaSerializer(schema)

250

251

# Data to serialize

252

data = {'name': 'Charlie', 'age': 35, 'active': True}

253

254

# Serialize to Python dict

255

python_result = serializer.to_python(data)

256

print(python_result) # {'name': 'Charlie', 'age': 35, 'active': True}

257

258

# Serialize to JSON

259

json_result = serializer.to_json(data)

260

print(json_result) # b'{"name":"Charlie","age":35,"active":true}'

261

262

# Serialize with formatting

263

formatted_json = serializer.to_json(data, indent=2)

264

print(formatted_json.decode())

265

# {

266

# "name": "Charlie",

267

# "age": 35,

268

# "active": true

269

# }

270

```

271

272

### Validation with Configuration

273

274

```python

275

from pydantic_core import SchemaValidator

276

from pydantic_core.core_schema import CoreConfig, str_schema, dict_schema

277

278

# Create configuration

279

config = CoreConfig(

280

strict=True,

281

str_strip_whitespace=True,

282

str_to_lower=True

283

)

284

285

# Create schema with config

286

schema = dict_schema({

287

'username': str_schema(min_length=3),

288

'password': str_schema(min_length=8)

289

})

290

291

validator = SchemaValidator(schema, config)

292

293

# This will strip whitespace and convert to lowercase

294

data = {'username': ' ALICE ', 'password': 'secretpassword'}

295

result = validator.validate_python(data)

296

print(result) # {'username': 'alice', 'password': 'secretpassword'}

297

```

298

299

### Error Handling

300

301

```python

302

from pydantic_core import SchemaValidator, ValidationError

303

from pydantic_core.core_schema import str_schema, int_schema, dict_schema

304

305

schema = dict_schema({

306

'name': str_schema(min_length=2),

307

'age': int_schema(ge=0, le=120)

308

})

309

310

validator = SchemaValidator(schema)

311

312

try:

313

# Invalid data

314

invalid_data = {'name': 'A', 'age': 150} # name too short, age too high

315

validator.validate_python(invalid_data)

316

except ValidationError as e:

317

print(f"Validation failed with {e.error_count()} errors:")

318

for error in e.errors():

319

print(f" {error['loc']}: {error['msg']}")

320

# Output:

321

# Validation failed with 2 errors:

322

# ('name',): String should have at least 2 characters

323

# ('age',): Input should be less than or equal to 120

324

```