sarala icon indicating copy to clipboard operation
sarala copied to clipboard

how to POST with relationship

Open asadhshujau opened this issue 5 years ago • 5 comments

https://jsonapi.org/format/#crud-creating

how do i send post request with relationships

POST /photos HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": {
    "type": "photos",
    "attributes": {
      "title": "Ember Hamster",
      "src": "http://example.com/images/productivity.png"
    },
    "relationships": {
      "photographer": {
        "data": { "type": "people", "id": "9" }
      }
    }
  }
}

asadhshujau avatar Mar 17 '19 14:03 asadhshujau

@milroyfraser I would like to know about this as well. Simply assigning a loaded model to a relation property does not seem to work.

happyDemon avatar Apr 03 '19 14:04 happyDemon

@asadhshujau @happyDemon You can't. JSON API SPEC does't support that at the moment.

You should send separate requests to create related resources (ex. POST /people)

And only then, if needed, associate newly created related resources with your main resource. Again, with different request (sync/attach).

subotkevic avatar Jul 13 '19 21:07 subotkevic

@subotkevic I believe that @asadhshujau and @happyDemon are attempting to link existent resources in the request, not create new ones. In which case, that is inaccurate. See #30.

aidan-casey avatar Oct 21 '19 20:10 aidan-casey

That being said, it’s possible and works fine.

subotkevic avatar Oct 22 '19 02:10 subotkevic

a few years later still does not work :D or i am not getting it to work.

can you provide an example @subotkevic ?

my use case:

User model

name, email, hasOne Brand

Brand

name

I need to create a user with a Brand right away, but the library sends the brand key inside user attributes and not in the relationships key.

ionut-tanasa avatar Feb 08 '22 09:02 ionut-tanasa