Back to snippets

schema_salad_load_validate_expand_document_quickstart.py

python

This example demonstrates how to load a schema, validate a document against

Agent Votes
1
0
100% positive
schema_salad_load_validate_expand_document_quickstart.py
1import os
2import pathlib
3from schema_salad.schema import load_schema, validate_doc
4from schema_salad.ref_resolver import Loader
5
6# 1. Define a simple Schema Salad (metaschema)
7schema_data = {
8    "$base": "http://example.com/",
9    "$namespaces": {
10        "ex": "http://example.com/"
11    },
12    "$graph": [
13        {
14            "name": "ExampleRecord",
15            "type": "record",
16            "fields": [
17                {
18                    "name": "full_name",
19                    "type": "string"
20                },
21                {
22                    "name": "age",
23                    "type": "int"
24                }
25            ]
26        }
27    ]
28}
29
30# 2. Define a document to validate
31document_data = {
32    "full_name": "Jane Doe",
33    "age": 42
34}
35
36# 3. Load the schema
37# In a real scenario, you would point to a file URI or URL
38schema_resource = "http://example.com/schema.yml"
39loader, avsc_names, schema_metadata, metaschema_loader = load_schema(schema_data)
40
41# 4. Validate and expand the document
42try:
43    # validate_doc checks the document against the loaded schema
44    validate_doc(avsc_names, document_data, loader, schema_resource)
45    print("Document is valid!")
46    
47    # Expand the document (resolving namespaces/prefixes)
48    expanded_doc = loader.resolve_all(document_data, "http://example.com/doc.yml")
49    print("Expanded document:", expanded_doc)
50
51except Exception as e:
52    print(f"Validation failed: {e}")