### Crawling and Registering Subresources in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Explains how to discover and register subresources that are embedded within a main schema document. The example shows how to crawl a registry to make these subresources accessible by their URIs. Dependencies: 'referencing'. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 # Schema with embedded subschemas (subresources) main_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/main", "$defs": { "sub1": { "$id": "https://example.com/sub1", "$anchor": "sub1anchor", "type": "string" }, "sub2": { "$id": "https://example.com/sub2", "type": "number" } } } # Initially, subresources are not accessible registry = Registry().with_contents([ ("https://example.com/main", main_schema) ], default_specification=DRAFT202012) try: registry["https://example.com/sub1"] print("Found sub1") except Exception: print("sub1 not yet available") # This will print # Crawl to discover subresources crawled_registry = registry.crawl() # Now subresources are accessible sub1 = crawled_registry["https://example.com/sub1"] print(sub1.contents["type"]) # Output: "string" sub2 = crawled_registry["https://example.com/sub2"] print(sub2.contents["type"]) # Output: "number" # Anchors are also discovered anchor = crawled_registry.anchor("https://example.com/sub1", "sub1anchor") print(anchor.value.name) # Output: "sub1anchor" ``` -------------------------------- ### Initialize Empty Registry (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst Illustrates the creation of an empty referencing.Registry. Registries are immutable, so methods that modify them, like adding resources, return new registry instances. This is the starting point for building up a collection of resources. ```python from referencing import Registry initial_registry = Registry() ``` -------------------------------- ### Cache Retrieved Resources with HTTPLX (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This example demonstrates how to cache external resources fetched via httpx using the to_cached_resource decorator. The decorated function returns the raw text content, and the decorator handles JSON deserialization and resource creation, preventing repeated network calls for the same URI. ```python from referencing import Registry, Resource import httpx import referencing.retrieval @referencing.retrieval.to_cached_resource() def cached_retrieve_via_httpx(uri): return httpx.get(uri).text registry = Registry(retrieve=cached_retrieve_via_httpx) resolver = registry.resolver() print(resolver.lookup("https://json-schema.org/draft/2020-12/schema")) ``` -------------------------------- ### Custom Specifications for Non-JSON Schema Documents in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Provides a starting point for creating custom specifications to handle document types other than JSON Schema. This allows the referencing library to work with various schema languages or data formats. Dependencies: 'referencing'. ```python from referencing import Specification, Registry, Anchor, Resource # Example of how a custom specification might be defined and used # This is a conceptual outline, as the actual implementation depends on the specific format. # class MyCustomSpecification(Specification): # def canonical_uri(self, resource): # # Implementation to get canonical URI # pass # # def dereference(self, resource, subpath): # # Implementation to dereference a subpath # pass # # def is_canonical(self, resource): # # Implementation to check if canonical # pass # # To use it: # my_spec = MyCustomSpecification() # registry = Registry(default_specification=my_spec) # # ... then add contents using registry.with_contents(...) ``` -------------------------------- ### Create and Populate Registry with Resource (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst Demonstrates how to create a referencing.Resource with specific content and a specification (JSON Schema Draft 2020-12). It then adds this resource to a new referencing.Registry, associating it with a given URI. This method is useful for initializing a registry with known resources. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 resource = Resource(contents={"type": "integer"}, specification=DRAFT202012) registry = Registry().with_resource(uri="http://example.com/my/resource", resource=resource) print(registry) ``` -------------------------------- ### Create Resource using Specification Shorthand - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet presents a more concise way to create a Resource object using the 'create_resource' method provided by a specific JSON Schema specification object. It verifies the equality of a resource created this way versus one created directly. ```python import referencing.jsonschema another = { "$id": "urn:example:my-second-schema", "type": "integer" } second_again = referencing.jsonschema.DRAFT202012.create_resource(another) # print(second_again == second) # Assuming 'second' is defined as in previous example ``` -------------------------------- ### Add Schema Resource to Registry - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet shows how to load a JSON schema from a string, create a Resource object from it, and add it to an initial registry. It then demonstrates retrieving the schema's contents using its internal ID. ```python import json from referencing import Resource loaded = json.loads( """ { "$id": "urn:example:my-schema", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "integer" } """, ) resource = Resource.from_contents(loaded) # Assuming initial_registry is defined elsewhere # registry = resource @ initial_registry # print(registry.contents("urn:example:my-schema")) ``` -------------------------------- ### Dynamic Resource Retrieval with Caching in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Shows how to set up dynamic resource retrieval for schemas not initially in the registry, with optional caching. Includes a simple retrieval function and demonstrates using the '@to_cached_resource' decorator for efficient fetching. Dependencies: 'referencing', 'json'. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 from referencing.retrieval import to_cached_resource from referencing.exceptions import NoSuchResource import json # Simple retrieval function def simple_retrieve(uri): # Simulate fetching from filesystem or network schemas = { "https://example.com/remote/user": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": {"username": {"type": "string"}} }, "https://example.com/remote/product": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": {"sku": {"type": "string"}} } } if uri in schemas: return Resource.from_contents(schemas[uri]) raise NoSuchResource(ref=uri) # Create registry with retrieval function registry = Registry(retrieve=simple_retrieve) resolver = registry.resolver() # Access dynamically retrieved resource resolved = resolver.lookup("https://example.com/remote/user") print(resolved.contents["properties"]["username"]) # Output: {"type": "string"} # Using cached retrieval decorator @to_cached_resource() def cached_retrieve(uri): print(f"Fetching: {uri}") return json.dumps({ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string" }) registry_cached = Registry(retrieve=cached_retrieve) first = registry_cached.get_or_retrieve("urn:example:test") second = registry_cached.get_or_retrieve("urn:example:test") # Uses cached value print(first.value.contents) # Output: {"$schema": "...", "type": "string"} ``` -------------------------------- ### Populate and Lookup in Registry - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/index.rst Demonstrates how to populate a registry with a resource and then look up a specific part of that resource using a resolver. This pattern is typically used by JSON Schema implementations. ```python from referencing import Registry, Resource import referencing.jsonschema schema = Resource.from_contents( { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "urn:example:a-202012-schema", "$defs": { "nonNegativeInteger": { "$anchor": "nonNegativeInteger", "type": "integer", "minimum": 0, }, }, } ) registry = schema @ Registry() resolver = registry.resolver() resolved = resolver.lookup("urn:example:a-202012-schema#nonNegativeInteger") assert resolved.contents == { "$anchor": "nonNegativeInteger", "type": "integer", "minimum": 0, } ``` -------------------------------- ### Add Resource with Explicit Specification to Registry - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet demonstrates adding a Resource, created with an explicit specification, to an existing registry. It then shows how to retrieve the contents of this newly added resource. ```python # Assuming 'registry' is defined and 'second' Resource object exists # registry = second @ registry # print(registry.contents("urn:example:my-second-schema")) ``` -------------------------------- ### Creating Resources Source: https://context7.com/python-jsonschema/referencing/llms.txt This section details how to create `Resource` objects from contents, either by auto-detecting the specification or by explicitly assigning one. It also covers creating opaque resources. ```APIDOC ## Creating Resources from Contents ### Description Resource creation with automatic specification detection or explicit specification assignment. ### Method `Resource.from_contents(contents, specification=None)` `Specification.create_resource(contents)` `Resource.opaque(contents)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **contents**: (dict or list) The data to be wrapped in a Resource. - **specification**: (Specification, optional) The specification to use for interpreting the contents. If None, it will attempt to auto-detect from `$schema`. ### Request Example ```python from referencing import Resource, Specification from referencing.jsonschema import DRAFT202012 # Auto-detect specification from $schema keyword schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/person.schema.json", "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} } } resource = Resource.from_contents(schema) print(resource.id()) # Output: "https://example.com/person.schema.json" # Create with explicit specification resource_explicit = DRAFT202012.create_resource(schema) # Create opaque resource (no subresources or anchors) opaque_data = {"arbitrary": "data", "nested": {"values": [1, 2, 3]}} opaque_resource = Resource.opaque(opaque_data) print(opaque_resource.id()) # Output: None ``` ### Response #### Success Response (200) - **Resource** (object): A Resource object representing the provided contents. #### Response Example ```json { "id": "https://example.com/person.schema.json", "contents": { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/person.schema.json", "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} } } } ``` ``` -------------------------------- ### Building and Managing a Registry Source: https://context7.com/python-jsonschema/referencing/llms.txt This section covers the construction and management of `Registry` objects, including adding resources by URI, adding multiple resources, and using the `@` operator for resources with internal `$id` values. ```APIDOC ## Building and Managing a Registry ### Description Registry construction with resources, including adding resources by URI and using the @ operator for resources with internal IDs. ### Method `Registry()` `Registry.with_resource(uri, resource)` `Registry.with_contents(contents, default_specification=None)` `resource @ registry` `registry[uri]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **uri**: (str) The URI to associate with the resource. - **resource**: (Resource) The Resource object to add. - **contents**: (list of tuples) A list of (uri, contents) tuples to add. - **default_specification**: (Specification, optional) The default specification to use when adding contents if not otherwise specified within the content itself. ### Request Example ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 # Start with empty registry registry = Registry() # Add resource with explicit URI person_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": {"name": {"type": "string"}} } resource = DRAFT202012.create_resource(person_schema) registry = registry.with_resource("https://example.com/person", resource) # Add multiple resources at once address_schema = {"type": "object", "properties": {"street": {"type": "string"}}} phone_schema = {"type": "string", "pattern": "^[0-9-]+$"} registry = registry.with_contents([ ("https://example.com/address", address_schema), ("https://example.com/phone", phone_schema) ], default_specification=DRAFT202012) # Use @ operator for resources with $id schema_with_id = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/user", "type": "object" } user_resource = Resource.from_contents(schema_with_id) registry = user_resource @ registry # Retrieve from registry retrieved = registry["https://example.com/person"] print(retrieved.contents) # Output: person_schema contents ``` ### Response #### Success Response (200) - **Registry** (object): A new Registry object with the added resources. - **Resource** (object): The retrieved Resource object. #### Response Example ```json { "contents": { "type": "object", "properties": {"name": {"type": "string"}} } } ``` ``` -------------------------------- ### Working with Anchors in Python Referencing Source: https://context7.com/python-jsonschema/referencing/llms.txt Illustrates how to define and resolve anchors within schemas using the referencing library. It covers both plain name anchors and demonstrates how to retrieve and use anchors for resolving references. Dependencies: 'referencing'. ```python from referencing import Registry, Anchor from referencing.jsonschema import DRAFT202012 # Schema with anchors schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/tree", "$defs": { "node": { "$anchor": "node", "type": "object", "properties": { "value": {"type": "number"}, "children": { "type": "array", "items": {"$ref": "#node"} } } } } } registry = Registry().with_contents([ ("https://example.com/tree", schema) ], default_specification=DRAFT202012) # Crawl to discover anchors registry = registry.crawl() # Retrieve anchor retrieved_anchor = registry.anchor("https://example.com/tree", "node") print(retrieved_anchor.value.name) # Output: "node" # Resolve reference using anchor resolver = registry.resolver("https://example.com/tree") resolved = resolver.lookup("#node") print(resolved.contents["type"]) # Output: "object" ``` -------------------------------- ### Create JSON Schema Resources in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Demonstrates creating `Resource` objects from JSON content, with options for automatic specification detection or explicit assignment. It also shows how to create opaque resources that do not support subresources or anchors. Requires the 'referencing' library. ```python from referencing import Resource, Specification from referencing.jsonschema import DRAFT202012 # Auto-detect specification from $schema keyword schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/person.schema.json", "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} } } resource = Resource.from_contents(schema) print(resource.id()) # Output: "https://example.com/person.schema.json" # Create with explicit specification resource_explicit = DRAFT202012.create_resource(schema) # Create opaque resource (no subresources or anchors) opaque_data = {"arbitrary": "data", "nested": {"values": [1, 2, 3]}} opaque_resource = Resource.opaque(opaque_data) print(opaque_resource.id()) # Output: None ``` -------------------------------- ### Define and Use Custom Specification in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Demonstrates how to define a custom specification for a hypothetical document format by implementing methods like `id_of`, `subresources_of`, `anchors_in`, and `maybe_in_subresource`. It then shows how to create a resource using this custom specification and crawl it with a registry. ```python from referencing import Specification, Registry, Anchor # Define custom specification for a hypothetical document format def custom_id_of(contents): """Extract ID from 'identifier' field.""" if isinstance(contents, dict): return contents.get("identifier") return None def custom_subresources_of(contents): """Extract subresources from 'components' field.""" if isinstance(contents, dict): return contents.get("components", []) return [] def custom_anchors_in(specification, contents): """Extract anchors from 'references' field.""" if isinstance(contents, dict): for name, value in contents.get("references", {}).items(): yield Anchor( name=name, resource=specification.create_resource(value) ) def custom_maybe_in_subresource(segments, resolver, subresource): """Enter subresource when traversing 'components' field.""" if segments and segments[-1] == "components": return resolver.in_subresource(subresource) return resolver custom_spec = Specification( name="custom-format", id_of=custom_id_of, subresources_of=custom_subresources_of, anchors_in=custom_anchors_in, maybe_in_subresource=custom_maybe_in_subresource ) # Use custom specification document = { "identifier": "urn:custom:doc1", "data": {"key": "value"}, "components": [ {"identifier": "urn:custom:doc1:component1", "type": "widget"} ], "references": { "main": {"data": "reference target"} } } resource = custom_spec.create_resource(document) registry = resource @ Registry() crawled = registry.crawl() # Access main document print(crawled["urn:custom:doc1"].contents["data"]) # Output: {"key": "value"} # Access subresource print(crawled["urn:custom:doc1:component1"].contents["type"]) # Output: "widget" ``` -------------------------------- ### Create Resource with Explicit Specification - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet shows how to explicitly define the JSON Schema specification for a Resource when it's created. This is an alternative to relying on the '$schema' keyword in the schema's contents and avoids potential ambiguity. ```python import referencing.jsonschema another = { "$id": "urn:example:my-second-schema", "type": "integer" } second = Resource(contents=another, specification=referencing.jsonschema.DRAFT202012) ``` -------------------------------- ### Resolve Fragment and Absolute References in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Demonstrates how to resolve schema references within a registry. It covers resolving fragment-only references using a base URI and resolving absolute references to full schemas. Requires the 'referencing' library. ```python from referencing import Registry # Assume 'registry' and 'resolver' are already set up and populated with schemas # For demonstration purposes, let's create a mock registry and resolver class MockResolver: def lookup(self, ref): class MockResolvedRef: def __init__(self, contents): self.contents = contents if ref == "#/$defs/email": return MockResolvedRef("email definition") elif ref == "https://example.com/schemas/base": return MockResolvedRef("full base_schema") return None class MockRegistry: def resolver(self, base_uri=None): return MockResolver() registry = MockRegistry() resolver = MockRegistry().resolver() # Mock resolver # Resolve fragment-only reference resolver_at_base = registry.resolver("https://example.com/schemas/base") resolved_def = resolver_at_base.lookup("#/$defs/email") print(resolved_def.contents) # Output: email definition # Resolve absolute reference resolved_abs = resolver.lookup("https://example.com/schemas/base") print(resolved_abs.contents) # Output: full base_schema ``` -------------------------------- ### Dynamically Retrieve External Resources via HTTP - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet shows how to configure a Registry to dynamically retrieve external resources, such as JSON Schema metaschemas from the network, using an HTTP client like httpx. This is achieved by providing a 'retrieve' callable to the Registry constructor. ```python import referencing import httpx async def retrieve_from_network(uri): response = await httpx.get(str(uri)) response.raise_for_status() return response.json() # Initialize registry with the retrieve callable # registry = referencing.Registry(retrieve=retrieve_from_network) # Example of retrieving a metaschema (assuming it's available at the URL) # metaschema_uri = "https://json-schema.org/draft/2020-12/schema" # metaschema_resource = await registry.get(metaschema_uri) ``` -------------------------------- ### Handle Empty Pointers in Resource.pointer (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst This update addresses an issue where Resource.pointer did not correctly handle empty pointers, which are intended to refer to the root document. This fix ensures proper handling, though it primarily affects direct usage of the function as Resource.lookup already accounted for empty fragments. ```python def pointer(self) -> JSONPointer: """Return this resource's pointer.""" if self._pointer is ...: return JSONPointer.empty() return self._pointer ``` -------------------------------- ### Build and Manage Registries in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Illustrates how to construct and manage `Registry` objects in Python. This includes adding resources with explicit URIs, adding multiple resources at once, using the '@' operator for resources with internal '$id', and retrieving resources from the registry. Requires the 'referencing' library. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 # Start with empty registry registry = Registry() # Add resource with explicit URI person_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": {"name": {"type": "string"}} } resource = DRAFT202012.create_resource(person_schema) registry = registry.with_resource("https://example.com/person", resource) # Add multiple resources at once address_schema = {"type": "object", "properties": {"street": {"type": "string"}}} phone_schema = {"type": "string", "pattern": "^[0-9-]+$"} registry = registry.with_contents([ ("https://example.com/address", address_schema), ("https://example.com/phone", phone_schema) ], default_specification=DRAFT202012) # Use @ operator for resources with $id schema_with_id = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/user", "type": "object" } user_resource = Resource.from_contents(schema_with_id) registry = user_resource @ registry # Retrieve from registry retrieved = registry["https://example.com/person"] print(retrieved.contents) # Output: person_schema contents ``` -------------------------------- ### Support Anchors from Non-Canonical URIs (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst Enhances the library's ability to resolve anchors (like '#foo') even when they are part of non-canonical URIs. This means if a resource is registered under 'http://example.com', anchors within it, like 'http://example.com#foo', can now be successfully resolved, even if the resource internally declares a different canonical URI. ```python def lookup_anchor(self, uri: URI) -> Resource: ... # Implementation details omitted for brevity ``` -------------------------------- ### Retrieve Schema Contents from Registry - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet demonstrates how to print the contents of a specific resource within a registry by providing its URI. This is useful for verifying that a resource has been successfully added and is accessible. ```python # Assuming 'registry' is already populated with 'urn:example:my-schema' # print(registry.contents("urn:example:my-schema")) ``` -------------------------------- ### Handle Referencing Exceptions in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Illustrates how to handle common exceptions that can occur during reference resolution and resource retrieval using the `referencing` library. It covers `Unresolvable`, `PointerToNowhere`, `NoSuchAnchor`, `NoInternalID`, and `CannotDetermineSpecification`. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 from referencing import exceptions # Build test registry schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/schema", "$defs": { "email": {"type": "string"} } } registry = Registry().with_contents([ ("https://example.com/schema", schema) ], default_specification=DRAFT202012) resolver = registry.resolver() # Handle NoSuchResource try: resolved = resolver.lookup("https://example.com/nonexistent") except exceptions.Unresolvable as e: print(f"Cannot resolve: {e.ref}") # Output: Cannot resolve: https://example.com/nonexistent # Handle PointerToNowhere try: resolved = resolver.lookup("https://example.com/schema#/$defs/nonexistent") except exceptions.PointerToNowhere as e: print(f"Pointer error: {e}") # Output: Pointer does not exist # Handle NoSuchAnchor try: resolved = resolver.lookup("https://example.com/schema#missinganchor") except exceptions.NoSuchAnchor as e: print(f"Anchor '{e.anchor}' not found") # Output: Anchor 'missinganchor' not found # Handle NoInternalID resource_without_id = DRAFT202012.create_resource({"type": "string"}) try: registry_fail = resource_without_id @ Registry() except exceptions.NoInternalID as e: print("Resource has no $id") # Output: Resource has no $id # Handle CannotDetermineSpecification try: unknown_resource = Resource.from_contents({"custom": "format"}) except exceptions.CannotDetermineSpecification as e: print("Cannot auto-detect specification") ``` -------------------------------- ### Detect Specification Without Resource Construction (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst Introduces Specification.detect, a function that identifies the specification of a schema without the need to construct a full Resource object. This is useful for quickly determining the schema dialect. ```python def detect(contents: Any) -> Specification: ... # Implementation details omitted for brevity ``` -------------------------------- ### Combine Registries in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Shows how to merge multiple `referencing.Registry` instances into a single, unified registry. This is useful for managing resources defined across different specifications or versions, allowing for unified lookup and resolution. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012, DRAFT7 # Create separate registries registry1 = Registry().with_contents([ ("https://example.com/v1/user", { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object" }), ("https://example.com/v1/product", { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object" }) ], default_specification=DRAFT202012) registry2 = Registry().with_contents([ ("https://example.com/v2/user", { "$schema": "http://json-schema.org/draft-07/schema", "type": "object" }), ("https://example.com/v2/order", { "$schema": "http://json-schema.org/draft-07/schema", "type": "object" }) ], default_specification=DRAFT7) # Combine registries combined = registry1.combine(registry2) # Access resources from both registries print(len(combined)) # Output: 4 print("https://example.com/v1/user" in combined) # Output: True print("https://example.com/v2/order" in combined) # Output: True # Resolve references across combined registry resolver = combined.resolver() resolved = resolver.lookup("https://example.com/v1/user") print(resolved.contents["type"]) # Output: "object" ``` -------------------------------- ### Raise NoSuchResource for Nonexistent Resources (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst This change modifies the Registry.contents() method to consistently raise a NoSuchResource exception when a nonexistent resource is accessed, rather than a KeyError. This provides a more specific and intended error type for such scenarios. ```python def contents(self) -> dict: if self._contents is ...: raise NoSuchResource(self.current().uri) return self._contents ``` -------------------------------- ### Resolving References Source: https://context7.com/python-jsonschema/referencing/llms.txt This section explains how to use a `Resolver` to resolve references within a `Registry`. It covers relative references, fragments, JSON Pointers, and anchor resolution. ```APIDOC ## Resolving References with a Resolver ### Description Reference resolution including relative references, fragments, JSON Pointers, and anchor resolution. ### Method `Registry.resolver(base_uri)` `Resolver.lookup(reference)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **base_uri**: (str) The base URI for the resolver. - **reference**: (str) The reference string to resolve. ### Request Example ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 # Build registry with related schemas base_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/schemas/base", "$defs": { "email": { "type": "string", "format": "email" } } } user_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/schemas/user", "type": "object", "properties": { "email": {"$ref": "base#/$defs/email"}, "name": {"type": "string"} } } registry = Registry().with_contents([ ("https://example.com/schemas/base", base_schema), ("https://example.com/schemas/user", user_schema) ], default_specification=DRAFT202012) # Create resolver with base URI resolver = registry.resolver("https://example.com/schemas/user") # Resolve relative reference try: resolved = resolver.lookup("base#/$defs/email") print(resolved.contents) # Output: {"type": "string", "format": "email"} except Exception as e: print(f"Resolution failed: {e}") ``` ### Response #### Success Response (200) - **Resource** (object): The resolved Resource object. #### Response Example ```json { "contents": { "type": "string", "format": "email" } } ``` ``` -------------------------------- ### Handle Schema without $schema Keyword - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet illustrates the error handling when trying to create a Resource from a schema that lacks the '$schema' keyword. It shows the 'CannotDetermineSpecification' exception that is raised, indicating ambiguity in the schema's intended specification. ```python import json from referencing import Resource another = json.loads( """ { "$id": "urn:example:my-second-schema", "type": "integer" } """, ) # print(Resource.from_contents(another)) # This would raise an error ``` -------------------------------- ### Normalize IDs with Empty Fragments (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst Normalizes resource IDs that contain empty fragments (e.g., 'http://example.com#'). This normalization, which effectively removes the fragment, is done to align with newer specifications that discourage or disallow empty fragments and to ensure compatibility with older meta-schemas that used them. ```python def normalize_id(uri: URI) -> URI: if uri.fragment == '': return uri.without_fragment() return uri ``` -------------------------------- ### Retrieve Resource Contents from Registry (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst Shows how to access the contents of a resource stored within a referencing.Registry using its associated URI. This is a fundamental operation for retrieving and inspecting data that has been registered. ```python print(registry.contents("http://example.com/my/resource")) ``` -------------------------------- ### Retrieve Resources with HTTPLX (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet shows how to define a custom retrieval function using httpx to fetch JSON schema resources from a given URI. The function parses the JSON response and returns it as a referencing.Resource object. It's intended for use within a referencing.Registry. ```python from referencing import Registry, Resource import httpx def retrieve_via_httpx(uri): response = httpx.get(uri) return Resource.from_contents(response.json()) registry = Registry(retrieve=retrieve_via_httpx) resolver = registry.resolver() print(resolver.lookup("https://json-schema.org/draft/2020-12/schema")) ``` -------------------------------- ### Resolve JSON References with Resolver in Python Source: https://context7.com/python-jsonschema/referencing/llms.txt Shows how to resolve JSON references using a `Resolver` in Python, including handling relative references, fragments, JSON Pointers, and anchor resolution. It involves building a registry with related schemas and creating a resolver with a base URI. Requires the 'referencing' library. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 # Build registry with related schemas base_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/schemas/base", "$defs": { "email": { "type": "string", "format": "email" } } } user_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/schemas/user", "type": "object", "properties": { "email": {"$ref": "base#/$defs/email"}, "name": {"type": "string"} } } registry = Registry().with_contents([ ("https://example.com/schemas/base", base_schema), ("https://example.com/schemas/user", user_schema) ], default_specification=DRAFT202012) # Create resolver with base URI resolver = registry.resolver("https://example.com/schemas/user") # Resolve relative reference try: resolved = resolver.lookup("base#/$defs/email") print(resolved.contents) # Output: {"type": "string", "format": "email"} except Exception as e: print(f"Resolution failed: {e}") ``` -------------------------------- ### Add Resource without $id using explicit URI - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet demonstrates how to add a Resource that lacks an '$id' keyword to a registry by explicitly providing the desired URI using the 'with_resource' method. This allows the resource to be stored and retrieved under the specified URI. ```python # Assuming 'registry' and 'third' Resource object are defined # registry = registry.with_resource(uri="urn:example:my-third-schema", resource=third) ``` -------------------------------- ### Retrieve Resource with Explicitly Assigned URI - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet shows how to retrieve the contents of a resource that was added to the registry using an explicit URI, particularly when the resource itself did not originally contain an '$id'. ```python # Assuming 'registry' has 'urn:example:my-third-schema' added via with_resource # print(registry.contents("urn:example:my-third-schema")) ``` -------------------------------- ### Handle Resource without $id Keyword - Python Source: https://github.com/python-jsonschema/referencing/blob/main/docs/intro.rst This snippet illustrates the error that occurs when attempting to add a Resource without an '$id' keyword to a registry using the '@' operator. It shows the 'NoInternalID' exception, indicating that an explicit URI must be provided for such resources. ```python import json from referencing import Resource third = Resource( contents=json.loads("{"type": "integer"}"), specification=referencing.jsonschema.DRAFT202012, ) # registry = third @ registry # This would raise a referencing.exceptions.NoInternalID error ``` -------------------------------- ### Suggest Corrections for Invalid Anchor/Pointer Usage (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst This update aims to provide more helpful feedback to users who might misuse URI fragments. It specifically addresses cases like '#foo/bar', which is neither a valid plain name anchor nor a JSON Pointer, by suggesting corrections. ```python if not fragment.startswith('/'): # Suggest correction for invalid JSON Pointer usage ... else: # Handle valid JSON Pointer or plain name anchor ... ``` -------------------------------- ### Define Empty Registry Constant (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst Introduces referencing.jsonschema.EMPTY_REGISTRY, a pre-defined empty registry. This constant is primarily for convenience and type annotation, functioning identically to a newly initialized Registry(). ```python EMPTY_REGISTRY: Registry = Registry() ``` -------------------------------- ### Fix Handling of IDs with Empty Fragments (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst Corrects the library's behavior when dealing with resource IDs that have empty fragments. Previously, these were not handled consistently, and this fix ensures they are treated correctly, equating them to URIs without any fragment identifier. ```python def resolve_id(base_uri: URI, target_uri: URI) -> URI: resolved = base_uri.join(target_uri) if resolved.fragment == '': return resolved.without_fragment() return resolved ``` -------------------------------- ### Add Caching Decorator for Retrieval Functions (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst Introduces referencing.retrieval.to_cached_resource, a decorator designed to cache the results of retrieval functions. This is particularly useful for optimizing performance by avoiding repeated network or filesystem access when converting JSON text to resources. ```python def to_cached_resource(func: Callable[..., Resource]) -> Callable[..., Resource]: ... # Implementation details omitted for brevity ``` -------------------------------- ### Handle Boolean additionalProperties in Draft 4 (Python) Source: https://github.com/python-jsonschema/referencing/blob/main/CHANGELOG.rst Addresses a specific issue in Draft 4 of JSON Schema where 'additionalProperties' could be a boolean value, which was not treated as a schema but as a special allowed value. This fix ensures correct interpretation in such cases. ```python def validate_schema(schema: dict, instance: Any, spec: Specification) -> None: if spec.version == "draft4": if "additionalProperties" in schema and isinstance(schema["additionalProperties"], bool): # Handle boolean additionalProperties logic ... ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.