Search code examples
jsonjson-api

Correct null relationship in JSON API


I have a JSON API type with a relationship

relationships {
    fruit: {data: {id: 123, type: "fruits"}}
}

What do I do if an instance does not have a fruit relationship?

Should I do this

relationships {
    fruit: {data: {id: null, type: "fruits"}}
}

or this

relationships {
    fruit: {data: null}
}

or this

relationships {
    fruit: null
}

or something completely different?


Solution

  • Accordingly to the spec a resource linkage object may have these values:

    Resource linkage MUST be represented as one of the following:

    • null for empty to-one relationships.
    • an empty array ([]) for empty to-many relationships.
    • a single resource identifier object for non-empty to-one relationships.
    • an array of resource identifier objects for non-empty to-many relationships.

    https://jsonapi.org/format/#document-resource-object-linkage

    From your examples only

    "relationships": {
        "fruit": {
          "data": null
        }
    }
    

    is a valid relationship object accordingly to JSON:API specification.

    This relationship object tells your client that

    • the resource object has a relationship fruit,
    • that it's a to-one relationship,
    • and that there isn't any related resource.