0
# Core Validation Functions
1
2
Primary functions for schema creation, data loading, and validation that form the foundation of Yamale's functionality. These functions provide the essential API for programmatic YAML validation.
3
4
## Capabilities
5
6
### Schema Creation
7
8
Creates a schema object from a YAML schema file or content string, supporting custom validators and multiple parsers.
9
10
```python { .api }
11
def make_schema(path=None, parser="PyYAML", validators=None, content=None):
12
"""
13
Create a Schema object from a YAML schema file or content.
14
15
Parameters:
16
- path (str, optional): Path to YAML schema file
17
- parser (str): YAML parser to use - "PyYAML" (default) or "ruamel"
18
- validators (dict, optional): Custom validator dictionary, defaults to DefaultValidators
19
- content (str, optional): YAML schema content as string (alternative to path)
20
21
Returns:
22
Schema: Configured schema object ready for validation
23
24
Raises:
25
ValueError: If schema file is empty
26
SyntaxError: If schema contains syntax errors
27
"""
28
```
29
30
Usage examples:
31
32
```python
33
# From file
34
schema = yamale.make_schema('./person.yaml')
35
36
# From content string
37
schema = yamale.make_schema(content="""
38
name: str()
39
age: int(min=0, max=150)
40
""")
41
42
# With custom parser
43
schema = yamale.make_schema('./schema.yaml', parser='ruamel')
44
45
# With custom validators
46
from yamale.validators import DefaultValidators
47
custom_validators = DefaultValidators.copy()
48
custom_validators['custom'] = MyCustomValidator
49
schema = yamale.make_schema('./schema.yaml', validators=custom_validators)
50
51
# Or access built-in validators
52
print(f"Available validators: {list(DefaultValidators.keys())}")
53
string_validator_class = DefaultValidators['str']
54
```
55
56
### Data Loading
57
58
Loads YAML data from files or content strings for validation, returning data in the format expected by the validate function.
59
60
```python { .api }
61
def make_data(path=None, parser="PyYAML", content=None):
62
"""
63
Load YAML data from file or content string.
64
65
Parameters:
66
- path (str, optional): Path to YAML data file
67
- parser (str): YAML parser to use - "PyYAML" (default) or "ruamel"
68
- content (str, optional): YAML data content as string (alternative to path)
69
70
Returns:
71
list: List of (data, path) tuples for each YAML document
72
"""
73
```
74
75
Usage examples:
76
77
```python
78
# From file
79
data = yamale.make_data('./person.yaml')
80
81
# From content string
82
data = yamale.make_data(content="""
83
name: John Doe
84
age: 30
85
""")
86
87
# With ruamel parser for YAML 1.2 support
88
data = yamale.make_data('./data.yaml', parser='ruamel')
89
90
# Multiple documents in one file
91
data = yamale.make_data('./multi-doc.yaml') # Returns multiple (data, path) tuples
92
```
93
94
### Validation
95
96
Validates data against a schema with configurable strict mode and error handling options.
97
98
```python { .api }
99
def validate(schema, data, strict=True, _raise_error=True):
100
"""
101
Validate data against a schema.
102
103
Parameters:
104
- schema (Schema): Schema object created with make_schema()
105
- data (list): Data list created with make_data() - list of (data, path) tuples
106
- strict (bool): Enable strict mode - reject unexpected elements (default: True)
107
- _raise_error (bool): Whether to raise YamaleError on validation failure (default: True)
108
109
Returns:
110
list: List of ValidationResult objects
111
112
Raises:
113
YamaleError: If validation fails and _raise_error=True
114
"""
115
```
116
117
Usage examples:
118
119
```python
120
# Basic validation (raises error on failure)
121
results = yamale.validate(schema, data)
122
123
# Non-strict mode (allows extra fields)
124
results = yamale.validate(schema, data, strict=False)
125
126
# Return results without raising errors
127
results = yamale.validate(schema, data, _raise_error=False)
128
for result in results:
129
if not result.isValid():
130
print(f"Validation failed: {result}")
131
132
# Handle validation errors
133
try:
134
yamale.validate(schema, data)
135
print("All data is valid!")
136
except yamale.YamaleError as e:
137
print("Validation failed:")
138
for result in e.results:
139
if not result.isValid():
140
print(f" File: {result.data}")
141
for error in result.errors:
142
print(f" {error}")
143
```
144
145
### Complete Workflow Example
146
147
```python
148
import yamale
149
150
# Create schema from file
151
schema = yamale.make_schema('./user-schema.yaml')
152
153
# Load multiple data files
154
data_files = ['user1.yaml', 'user2.yaml', 'user3.yaml']
155
all_data = []
156
for file_path in data_files:
157
data = yamale.make_data(file_path)
158
all_data.extend(data)
159
160
# Validate all data
161
try:
162
results = yamale.validate(schema, all_data)
163
print(f"Successfully validated {len(all_data)} documents")
164
except yamale.YamaleError as e:
165
print(f"Validation failed for {len([r for r in e.results if not r.isValid()])} documents")
166
for result in e.results:
167
if not result.isValid():
168
print(f" {result.data}: {'; '.join(result.errors)}")
169
```
170
171
## Error Handling
172
173
All core functions may raise standard Python exceptions:
174
175
- **ValueError**: Invalid parameters or empty schema files
176
- **SyntaxError**: Schema syntax errors or invalid YAML
177
- **FileNotFoundError**: When specified file paths don't exist
178
- **yaml.YAMLError**: YAML parsing errors from the underlying parser
179
180
The `validate()` function specifically raises `YamaleError` when validation fails and `_raise_error=True` (default behavior).