Eric Broda
Eric Broda

Reputation: 7241

JSON Schema reference using an empty fragment

I am using OpenAPI specifications and have found reference tags that point to an empty string (empty fragment). Is this a correct reference? If yes, how is this reference to be interpreted? What does it point to, and what value is determined to be correct when the OpenAPI spec is validated?

I have examined the OpenAPI drafts as well as JSON Schema drafts but they do not mention how to handle this, nor do they have any examples or guidance on what constitutes correct behaviour.

Any help is appreciated.

Below is an example... note under the Amount/Amount there is a "$ref": ""

(this example is a portion of Balances specification in the UK Open Banking model)

:
:
"Amount": {
  "type": "object",
  "required": [
    "Amount",
    "Currency"
  ],
  "description": "Amount of money of the cash balance.",
  "properties": {
    "Amount": {
      "$ref": ""
    },
    "Currency": {
      "$ref": "#/components/schemas/ActiveOrHistoricCurrencyCode_1"
    }
  }
}
:
:

Upvotes: 1

Views: 507

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

The reason you don't find this spelled out in either spec is because both defer to RFC-3986 to define how URIs are resolved. That means URI resolution in JSON Schema and OpenAPI work exactly the same as HTML and therefore should be familiar to most web developers. The Understanding JSON Schema site has a section that explains how RFC-3986 URI resolution works in the context of JSON Schema.

In this case, the base URI is the location of the document. It might be on the file system: file:///path/to/myapi.openapi.json, or it might be on web http://example.com/myapi.openapi.json. The relative reference URI found in $ref is resolved against this base URI. Resolving an empty relative reference against the base URI results in a URI that is the same as the base URI.

That means that in your example, this $ref is referencing an OpenAPI document instead of a JSON Schema, which is not allowed in JSON Schema. A $ref in a JSON Schema can only reference a JSON Schema. This appears to be an error in the OpenAPI document you're working with.

However, that doesn't mean an empty $ref is always invalid. In a JSON Schema document (not embedded in an OpenAPI document) you could use this to define a recursive structure. Usually you'll see recursive references defined as "$ref": "#" instead of being empty, but there isn't any good reason to include the #. You should end up in the same place either way.

Upvotes: 0

Related Questions