High-performance JSON schema validation library for Python with support for JSON Schema drafts 04, 06, and 07.
npx @tessl/cli install tessl/pypi-fastjsonschema@2.21.00
# Fastjsonschema
1
2
A high-performance JSON schema validation library for Python that implements JSON Schema drafts 04, 06, and 07. It generates optimized validation code on-the-fly to achieve exceptional performance, being significantly faster than popular alternatives like jsonschema and json-spec.
3
4
## Package Information
5
6
- **Package Name**: fastjsonschema
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install fastjsonschema`
10
11
## Core Imports
12
13
```python
14
import fastjsonschema
15
```
16
17
Common imports for validation:
18
19
```python
20
from fastjsonschema import compile, validate, JsonSchemaValueException
21
```
22
23
## Basic Usage
24
25
```python
26
import fastjsonschema
27
28
# Define a JSON schema
29
schema = {
30
"type": "object",
31
"properties": {
32
"name": {"type": "string"},
33
"age": {"type": "number", "minimum": 0},
34
"email": {"type": "string", "format": "email"}
35
},
36
"required": ["name", "age"],
37
"additionalProperties": False
38
}
39
40
# Method 1: Compile for reuse (recommended for performance)
41
validate_person = fastjsonschema.compile(schema)
42
43
try:
44
# Valid data
45
result = validate_person({"name": "John", "age": 30, "email": "john@example.com"})
46
print("Valid:", result)
47
48
# Invalid data will raise an exception
49
validate_person({"name": "John", "age": -5})
50
except fastjsonschema.JsonSchemaValueException as e:
51
print(f"Validation error: {e.message}")
52
print(f"Invalid value: {e.value}")
53
print(f"Path: {e.path}")
54
55
# Method 2: One-time validation (less performant)
56
try:
57
fastjsonschema.validate(schema, {"name": "Jane", "age": 25})
58
except fastjsonschema.JsonSchemaValueException as e:
59
print(f"Validation failed: {e}")
60
```
61
62
## Architecture
63
64
Fastjsonschema works by generating optimized Python validation code based on the provided JSON schema. The library supports:
65
66
- **Draft Support**: JSON Schema drafts 04, 06, and 07
67
- **Code Generation**: Compiles schemas into fast validation functions
68
- **Custom Formats**: Support for custom format validators
69
- **Reference Resolution**: Full $ref support including remote schemas
70
- **Default Values**: Automatic application of default values from schemas
71
- **Performance Optimization**: Generated code is significantly faster than interpreter-based validation
72
73
## Capabilities
74
75
### Schema Compilation
76
77
Compiles JSON schemas into optimized validation functions for maximum performance when validating multiple data instances.
78
79
```python { .api }
80
def compile(definition, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):
81
"""
82
Generates validation function for validating JSON schema passed in definition.
83
84
Args:
85
definition (dict): JSON schema definition
86
handlers (dict): Mapping from URI to function for retrieving remote schemas
87
formats (dict): Custom format validators (regex strings or callables)
88
use_default (bool): Apply default values from schema (default: True)
89
use_formats (bool): Use format assertions (default: True)
90
detailed_exceptions (bool): Include detailed error information (default: True)
91
92
Returns:
93
function: Compiled validation function that takes data and returns validated data
94
95
Raises:
96
JsonSchemaDefinitionException: When schema compilation fails
97
"""
98
```
99
100
### One-time Validation
101
102
Validates data against a schema in a single call, suitable for occasional validations where performance is not critical.
103
104
```python { .api }
105
def validate(definition, data, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):
106
"""
107
Validation function for lazy programmers or for use cases when you need
108
to call validation only once.
109
110
Args:
111
definition (dict): JSON schema definition
112
data: Data to validate against the schema
113
handlers (dict): Mapping from URI to function for retrieving remote schemas
114
formats (dict): Custom format validators (regex strings or callables)
115
use_default (bool): Apply default values from schema (default: True)
116
use_formats (bool): Use format assertions (default: True)
117
detailed_exceptions (bool): Include detailed error information (default: True)
118
119
Returns:
120
Validated data (potentially with defaults applied)
121
122
Raises:
123
JsonSchemaValueException: When validation fails
124
JsonSchemaDefinitionException: When schema compilation fails
125
"""
126
```
127
128
### Code Generation
129
130
Generates validation code as a string that can be saved to files for even better performance or standalone deployment.
131
132
```python { .api }
133
def compile_to_code(definition, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):
134
"""
135
Generates validation code for validating JSON schema passed in definition.
136
137
Args:
138
definition (dict): JSON schema definition
139
handlers (dict): Mapping from URI to function for retrieving remote schemas
140
formats (dict): Custom format validators (regex strings or callables)
141
use_default (bool): Apply default values from schema (default: True)
142
use_formats (bool): Use format assertions (default: True)
143
detailed_exceptions (bool): Include detailed error information (default: True)
144
145
Returns:
146
str: Python code string containing validation function
147
148
Raises:
149
JsonSchemaDefinitionException: When schema compilation fails
150
"""
151
```
152
153
### Command-Line Interface
154
155
Generate validation code directly from the command line using the built-in CLI interface.
156
157
```bash
158
# Generate validation code from schema passed as argument
159
python -m fastjsonschema '{"type": "string", "minLength": 5}' > validator.py
160
161
# Generate validation code from schema via stdin
162
echo '{"type": "number", "maximum": 100}' | python -m fastjsonschema > validator.py
163
164
# Use with files
165
python -m fastjsonschema "$(cat schema.json)" > validator.py
166
```
167
168
The generated code can then be imported and used directly:
169
170
```python
171
# Content of generated validator.py file
172
from validator import validate_data
173
174
try:
175
result = validate_data("hello world") # Valid
176
print("Valid:", result)
177
except Exception as e:
178
print("Invalid:", e)
179
```
180
181
### Custom Formats
182
183
Support for custom format validation through regular expressions or callable functions.
184
185
```python
186
# Using regular expressions
187
custom_formats = {
188
'custom-id': r'^[A-Z]{2}-\d{4}$', # e.g., "AB-1234"
189
}
190
191
# Using callable functions
192
def validate_phone(value):
193
"""Custom phone number validator"""
194
if not isinstance(value, str):
195
return False
196
# Remove spaces and dashes
197
cleaned = value.replace(' ', '').replace('-', '')
198
return cleaned.isdigit() and len(cleaned) == 10
199
200
custom_formats = {
201
'phone': validate_phone
202
}
203
204
# Use with compile
205
validator = fastjsonschema.compile(schema, formats=custom_formats)
206
```
207
208
### Remote Schema Resolution
209
210
Handle external schema references through custom URI handlers.
211
212
```python
213
def http_handler(uri):
214
"""Custom handler for HTTP URIs"""
215
import requests
216
response = requests.get(uri)
217
return response.json()
218
219
handlers = {
220
'http': http_handler,
221
'https': http_handler
222
}
223
224
# Schema with remote reference
225
schema = {
226
"$ref": "https://json-schema.org/draft-07/schema#"
227
}
228
229
validator = fastjsonschema.compile(schema, handlers=handlers)
230
```
231
232
### Default Value Application
233
234
Automatic application of default values specified in the schema.
235
236
```python
237
schema = {
238
"type": "object",
239
"properties": {
240
"name": {"type": "string"},
241
"status": {"type": "string", "default": "active"},
242
"count": {"type": "integer", "default": 0}
243
}
244
}
245
246
validator = fastjsonschema.compile(schema, use_default=True)
247
248
# Input data with missing optional fields
249
data = {"name": "John"}
250
251
# Validation applies defaults
252
result = validator(data)
253
# result = {"name": "John", "status": "active", "count": 0}
254
```
255
256
## Exception Handling
257
258
### JsonSchemaValueException
259
260
Raised when data validation fails, providing detailed information about the validation error.
261
262
```python { .api }
263
class JsonSchemaValueException(JsonSchemaException):
264
"""
265
Exception raised by validation function.
266
267
Attributes:
268
message (str): Human-readable information about the error
269
value: The invalid value that caused the exception
270
name (str): Path string in the data structure (e.g., "data.property[index]")
271
path (list): Path as array in the data structure (computed property)
272
definition (dict): The schema definition that failed
273
rule (str): The specific schema rule that was violated
274
rule_definition: The value of the violated rule (computed property)
275
"""
276
```
277
278
### JsonSchemaDefinitionException
279
280
Raised when schema compilation fails due to invalid or malformed schema.
281
282
```python { .api }
283
class JsonSchemaDefinitionException(JsonSchemaException):
284
"""
285
Exception raised by generator of validation function when schema is invalid.
286
"""
287
```
288
289
### JsonSchemaException
290
291
Base exception class for all fastjsonschema exceptions.
292
293
```python { .api }
294
class JsonSchemaException(ValueError):
295
"""
296
Base exception of fastjsonschema library.
297
"""
298
```
299
300
## Advanced Usage Examples
301
302
### Error Handling with Detailed Information
303
304
```python
305
import fastjsonschema
306
307
schema = {
308
"type": "object",
309
"properties": {
310
"items": {
311
"type": "array",
312
"items": {"type": "number", "maximum": 100}
313
}
314
}
315
}
316
317
validator = fastjsonschema.compile(schema)
318
319
try:
320
validator({"items": [10, 50, 150, 75]})
321
except fastjsonschema.JsonSchemaValueException as e:
322
print(f"Error message: {e.message}")
323
print(f"Invalid value: {e.value}") # 150
324
print(f"Location path: {e.name}") # "data.items[2]"
325
print(f"Path array: {e.path}") # ["data", "items", "2"]
326
print(f"Violated rule: {e.rule}") # "maximum"
327
print(f"Rule value: {e.rule_definition}") # 100
328
```
329
330
### Performance Optimization
331
332
```python
333
# For maximum performance, disable detailed exceptions
334
validator = fastjsonschema.compile(schema, detailed_exceptions=False)
335
336
# For even better performance, generate code to file
337
code = fastjsonschema.compile_to_code(schema)
338
with open('validator.py', 'w') as f:
339
f.write(code)
340
341
# Then import and use the generated validator
342
# from validator import validate_data
343
```
344
345
### Schema Draft Selection
346
347
```python
348
# Schema draft is auto-detected from $schema field
349
draft04_schema = {
350
"$schema": "http://json-schema.org/draft-04/schema#",
351
"type": "string"
352
}
353
354
draft07_schema = {
355
"$schema": "http://json-schema.org/draft-07/schema#",
356
"type": "string"
357
}
358
359
# If no $schema specified, defaults to draft-07
360
validator = fastjsonschema.compile({"type": "number"})
361
```
362
363
## Version Information
364
365
```python { .api }
366
VERSION = "2.21.2"
367
```
368
369
Access the library version:
370
371
```python
372
import fastjsonschema
373
print(fastjsonschema.VERSION) # "2.21.2"
374
```
375
376
## Types
377
378
```python { .api }
379
# Handler function type for remote schema resolution
380
def handler_function(uri: str) -> dict:
381
"""
382
Custom handler for resolving remote schema URIs.
383
384
Args:
385
uri: The URI to resolve
386
387
Returns:
388
dict: The resolved schema as a dictionary
389
"""
390
391
# Format validator function type
392
def format_validator(value: str) -> bool:
393
"""
394
Custom format validator function.
395
396
Args:
397
value: The string value to validate
398
399
Returns:
400
bool: True if valid, False otherwise. Can also raise exceptions.
401
"""
402
403
# Compiled validator function type
404
def validation_function(data) -> any:
405
"""
406
Compiled validation function returned by compile().
407
408
Args:
409
data: Data to validate against the compiled schema
410
411
Returns:
412
Validated data (potentially with defaults applied)
413
414
Raises:
415
JsonSchemaValueException: When validation fails
416
"""
417
```