@@ -74,6 +74,60 @@ implemented here, across any other implementation they encounter.
74
74
the object which implements format validation
75
75
76
76
77
+ How do I configure a base URI for ``$ref `` resolution using local files?
78
+ ------------------------------------------------------------------------
79
+
80
+ `jsonschema ` supports loading schemas from the filesystem.
81
+
82
+ The most common mistake when configuring a :class: `~jsonschema.RefResolver `
83
+ to retrieve schemas from the local filesystem is to give it a base URI
84
+ which points to a directory, but forget to add a trailing slash.
85
+
86
+ For example, given a directory ``/tmp/foo/ `` with ``bar/schema.json ``
87
+ within it, you should use something like:
88
+
89
+ .. code-block :: python
90
+
91
+ from pathlib import Path
92
+
93
+ import jsonschema.validators
94
+
95
+ path = Path(" /tmp/foo" )
96
+ resolver = jsonschema.validators.RefResolver(
97
+ base_uri = f " { path.as_uri()} / " ,
98
+ referrer = True ,
99
+ )
100
+ jsonschema.validate(
101
+ instance = {},
102
+ schema = {" $ref" : " bar/schema.json" },
103
+ resolver = resolver,
104
+ )
105
+
106
+ where note:
107
+
108
+ * the base URI has a trailing slash, even though
109
+ `pathlib.PurePath.as_uri ` does not add it!
110
+ * any relative refs are now given relative to the provided directory
111
+
112
+ If you forget the trailing slash, you'll find references are resolved a
113
+ directory too high.
114
+
115
+ You're likely familiar with this behavior from your browser. If you
116
+ visit a page at ``https://example.com/foo ``, then links on it like
117
+ ``<a href="./bar"> `` take you to ``https://example.com/bar ``, not
118
+ ``https://example.com/foo/bar ``. For this reason many sites will
119
+ redirect ``https://example.com/foo `` to ``https://example.com/foo/ ``,
120
+ i.e. add the trailing slash, so that relative links on the page will keep the
121
+ last path component.
122
+
123
+ There are, in summary, 2 ways to do this properly:
124
+
125
+ * Remember to include a trailing slash, so your base URI is
126
+ ``file:///foo/bar/ `` rather than ``file:///foo/bar ``, as shown above
127
+ * Use a file within the directory as your base URI rather than the
128
+ directory itself, i.e. ``file://foo/bar/baz.json ``, which will of course
129
+ cause ``baz.json `` to be removed while resolving relative URIs
130
+
77
131
Why doesn't my schema's default property set the default on my instance?
78
132
------------------------------------------------------------------------
79
133
0 commit comments