0
# JSON Schema Validation
1
2
Comprehensive JSON schema validation for Poetry configuration files and internal data structures. Poetry Core uses JSON schemas to validate pyproject.toml configurations and ensure data integrity.
3
4
## Core Import
5
6
```python
7
from poetry.core.json import validate_object, ValidationError
8
``` { .api }
9
10
## Capabilities
11
12
### Object Validation
13
14
Validates Python dictionaries against predefined JSON schemas for Poetry configuration.
15
16
```python { .api }
17
def validate_object(obj: dict[str, Any], schema_name: str) -> list[str]:
18
"""
19
Validate a Python object against a JSON schema.
20
21
Args:
22
obj: Dictionary to validate
23
schema_name: Name of schema file (without .json extension)
24
25
Returns:
26
List of validation error messages. Empty list if valid.
27
28
Raises:
29
ValueError: If schema file does not exist
30
31
Available Schemas:
32
- "poetry-schema": Validates [tool.poetry] configuration
33
- "project-schema": Validates [project] PEP 621 configuration
34
"""
35
```
36
37
### Validation Exception
38
39
```python { .api }
40
class ValidationError(ValueError):
41
"""
42
Exception raised for JSON schema validation failures.
43
44
Inherits from ValueError and provides additional context
45
for schema validation errors.
46
"""
47
```
48
49
## Usage Examples
50
51
### Validating Poetry Configuration
52
53
```python
54
from poetry.core.json import validate_object, ValidationError
55
from poetry.core.pyproject.toml import PyProjectTOML
56
from pathlib import Path
57
58
# Load pyproject.toml
59
pyproject_path = Path("pyproject.toml")
60
pyproject = PyProjectTOML(pyproject_path)
61
62
# Validate Poetry configuration section
63
poetry_config = pyproject.poetry_config
64
errors = validate_object(poetry_config, "poetry-schema")
65
66
if errors:
67
print("Poetry configuration errors:")
68
for error in errors:
69
print(f" - {error}")
70
else:
71
print("Poetry configuration is valid")
72
```
73
74
### Validating PEP 621 Project Configuration
75
76
```python
77
from poetry.core.json import validate_object
78
from poetry.core.pyproject.toml import PyProjectTOML
79
from pathlib import Path
80
81
# Load and validate PEP 621 [project] section
82
pyproject = PyProjectTOML(Path("pyproject.toml"))
83
84
# Get project configuration if present
85
if "project" in pyproject.data:
86
project_config = pyproject.data["project"]
87
errors = validate_object(project_config, "project-schema")
88
89
if errors:
90
print("Project configuration errors:")
91
for error in errors:
92
print(f" - {error}")
93
else:
94
print("Project configuration is valid")
95
```
96
97
### Error Handling with ValidationError
98
99
```python
100
from poetry.core.json import validate_object, ValidationError
101
102
# Example of handling validation with try/catch
103
try:
104
config = {
105
"name": "my-package",
106
"version": "1.0.0",
107
# Missing required fields or invalid structure
108
}
109
110
errors = validate_object(config, "poetry-schema")
111
112
if errors:
113
# Create ValidationError with detailed message
114
error_message = "Configuration validation failed:\n" + "\n".join(errors)
115
raise ValidationError(error_message)
116
117
except ValidationError as e:
118
print(f"Validation failed: {e}")
119
except ValueError as e:
120
print(f"Schema error: {e}")
121
```
122
123
### Custom Validation Function
124
125
```python
126
from poetry.core.json import validate_object
127
from typing import Any
128
129
def validate_poetry_config(config: dict[str, Any]) -> bool:
130
"""
131
Helper function to validate Poetry configuration.
132
133
Args:
134
config: Poetry configuration dictionary
135
136
Returns:
137
True if valid, False otherwise
138
"""
139
try:
140
errors = validate_object(config, "poetry-schema")
141
return len(errors) == 0
142
except ValueError:
143
# Schema not found or other validation setup error
144
return False
145
146
# Usage
147
config = {
148
"name": "my-package",
149
"version": "1.0.0",
150
"description": "A sample package"
151
}
152
153
if validate_poetry_config(config):
154
print("Configuration is valid")
155
else:
156
print("Configuration has errors")
157
```
158
159
## Available Schemas
160
161
Poetry Core includes two main JSON schemas:
162
163
### 1. Poetry Schema (`poetry-schema`)
164
165
Validates the `[tool.poetry]` section of pyproject.toml files. This schema ensures:
166
167
- **Required fields**: `name`, `version`, `description`
168
- **Optional fields**: `authors`, `maintainers`, `license`, `readme`, etc.
169
- **Dependencies**: Proper structure for `dependencies` and `group` sections
170
- **Build settings**: Valid `packages`, `include`, `exclude` configurations
171
- **Metadata**: Valid `keywords`, `classifiers`, `urls`
172
173
### 2. Project Schema (`project-schema`)
174
175
Validates PEP 621 `[project]` section configuration. This schema ensures:
176
177
- **Core metadata**: `name`, `version`, `description`, `authors`
178
- **Dependencies**: PEP 508 dependency specifications
179
- **Optional dependencies**: Extra groups and optional dependency sets
180
- **Classifiers**: Valid PyPI trove classifiers
181
- **URLs**: Project homepage, repository, documentation links
182
183
## Schema Integration
184
185
The JSON validation integrates seamlessly with Poetry Core's configuration system:
186
187
```python
188
from poetry.core.factory import Factory
189
from poetry.core.pyproject.toml import PyProjectTOML
190
from pathlib import Path
191
192
# Factory validation includes JSON schema validation
193
project_path = Path("/path/to/project")
194
pyproject = PyProjectTOML(project_path / "pyproject.toml")
195
196
# Validate entire configuration
197
validation_errors = Factory.validate(pyproject.data)
198
199
if validation_errors:
200
for section, errors in validation_errors.items():
201
print(f"Errors in [{section}]:")
202
for error in errors:
203
print(f" - {error}")
204
```
205
206
## Internal Implementation
207
208
The validation system uses `fastjsonschema` for high-performance validation:
209
210
- **Fast compilation**: Schemas are compiled to Python functions
211
- **Detailed errors**: Provides specific error messages with field paths
212
- **Schema loading**: Automatically loads schemas from internal resources
213
- **Error formatting**: Converts JSON schema errors to readable messages
214
215
## Best Practices
216
217
### 1. Validate Early
218
```python
219
# Validate configuration immediately after loading
220
pyproject = PyProjectTOML(path)
221
errors = validate_object(pyproject.poetry_config, "poetry-schema")
222
if errors:
223
raise ValidationError(f"Invalid configuration: {errors}")
224
```
225
226
### 2. Handle Missing Schemas Gracefully
227
```python
228
try:
229
errors = validate_object(config, "custom-schema")
230
except ValueError as e:
231
if "does not exist" in str(e):
232
print("Schema not available, skipping validation")
233
else:
234
raise
235
```
236
237
### 3. Provide User-Friendly Error Messages
238
```python
239
def format_validation_errors(errors: list[str]) -> str:
240
"""Format validation errors for user display."""
241
if not errors:
242
return "Configuration is valid"
243
244
formatted = "Configuration validation failed:\n"
245
for i, error in enumerate(errors, 1):
246
formatted += f" {i}. {error}\n"
247
248
return formatted.strip()
249
```