Pattern: handling unstable IDs


#1

I have a model whose ID is unstable. Examples of this might be using a username, email address, or blog post title as a primary ID. Most uses of JSON:API I’ve seen use stable, surrogate (or “synthetic”) keys and this is generally a good practice. Sometimes, however, you can’t change the model.

An unstable ID is a problem for JSON:API because if you make an update via PATCH, you might change the one or more fields that cause the ID to change. In that case, the response object will have an ID that doesn’t match what you sent or what’s in the URL.

My proposal for this pattern is that the response includes no data but does have an included:

PATCH /songs/never-gonna-give-you-up
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
{
  "data": {
    "id": "never-gonna-give-you-up",
    "type": "song",
    "attributes": {
      "title": "Please don't Rick-roll me",
    }
  }
}

200 OK
Content-Type: application/vnd.api+json
{
  included: [{
    "data": {
      "id": "please-dont-rick-roll-me",
      "type": "song",
      "attributes": {
        "title": "Please don't Rick-roll me",
      }
    }
  }]
}

What do people think?