Updating resources: why duplicate id both in URL and request body?

I wonder what’s the reasoning behind sending the resource’s id both as URL param and request.body.data.id, as presented in Resources > Updating Resources

The PATCH request MUST include a single resource object as primary data. The resource object MUST contain type and id members.

PATCH /articles/1
{
  "data": {
    "id": "1"
  }
}

Why would you not include the ID in the body?

The client sends a request with the ID in the URL and the response it gets back includes the ID (if the resource was found).

Do you think it is redundant to have the ID in the body since the client should already know what the ID is?

The ID is present because it’s part of the resource. Figuring out what the client already knows so that the response be a few bytes smaller adds complexity and reduces convenience for almost no benefits at all.

For example, I have a library for marshaling and unmarshaling JSON:API payloads in Go. I have a one function that can marshal a single resource into a JSON payload. To save a few bytes, I would have to add extra logic to check if the resource is used a primary data (but not part of a collection) and if so, do not include the ID. What do I really gain from that? It’s reasonable to say that most libraries function in a similar way.

I knew I had missed something. You are talking about PATCH requests.

In that case, I’m not sure what the answer is. I would guess that it’s for being consistent wit the rest of the API specification.

It makes it possible to change the ID of a resource, if that’s something your server chooses to support:

PATCH /articles/1
{
  "data": {
    "id": "2"
  }
}
1 Like

Thanks for answering. Do you know any real life use case of this particular need?

I have definitely seen systems in the past that wanted to edit IDs. It’s often because of an earlier data modeling mistake, but real systems may be stuck with such mistakes.

The best advice these days is to never try to use a natural ID, meaning some pre-existing data about your record is the id. Sometimes people do things like use a social security number or other government-issued id number or phone number as an id. And then later they realize, “oops, that might actually need to change!”.