Creating/updating a resource AND its relationships


#1

I know there are multiple topics and discussions on allowing multiple actions for request, but i havent found anything specific to my use case.

Say for example i have a “user” resource, which also has many “user_meta” resources.

getting it is fine, and updating relations by providing ids is fine, but consider this scenario:

I want to register a user and as part of this add new user meta (address, phone, etc).

How would the post request look? it doesnt seem to documented.

And then another scenario, i have a created user resource, and i want to create and attach a new user meta field.

According to my enterpritation this would mean:

  1. fetch the user via get /users/{id}?include=user_meta including all the meta relationships
  2. make a post to /user_meta to create the resource and fetch its id
  3. make a patch request to /users/{id}/relationships/user_meta with all the ids fetched in step 1 AND the new id provided in step 2.

It does mention you can update relationships via the resource patch method, but its example only provides how to update existing relationship resources.

would this be valid:

PATCH /articles/1 HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": {
    "type": "user",
    "id": "1",
    "attributes": {
      "name": "new name"
    }
  },
"included": [{
    "type": "user_meta",
    "id": null,
    "attributes": {
      "key": "address_1",
      "value": "street name"
    }
  }]
}

This would use the includes object, but the includes resource doesnt yet exist, so has an id of null, so instead of just updating the user resource, it would also create the related resource and attach its relationship.

would this be valid?


#2

Right… this falls under the need for multiple actions in a single request, which isn’t supported quite yet. (Though the progress in #915 is a big step, as it unblocks #795.)

Is it ok for you to do it in two requests? If so, then it’s simple (using the same process as in the case below).

This is actually doable in one or two requests, and it doesn’t require "included" (the behavior of which is only defined for GET requests).

Here’s how you do it. Either:

  1. POST to /user_metas to create the resource, and then POST its type/id to /users/{id}/relationships/user_meta. The second POST will add the new item onto the end, so you don’t have to get the existing ids in the relationship and send them back.

  2. If you have a "related" URI for your user resource’s user_meta relationship (probably a URI like /users/{id}/user_metas), you can POST the new user_meta to that directly and it should be created and added to the relationship. (For background on the related link, see: Usage of `related` field in Relationships link)