David
David

Reputation: 10748

How to create a child entity in to-many relationship with JSONAPI

I've been reading through jsonapi's docs and I can't wrap my head around how this is practical. According to the docs to add a comment to an article the comment must already exist.

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

{
  "data": [
    { "type": "comments", "id": "123" }
  ]
}

Is this just a poor example or does the spec really want you to issue a request to create a comment that isn't related to an entity before issuing the above request to relate it for a total of 2 requests?

It would seem that you would more likely want to issue a request like this:

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

{
  "data": {
    "type": "comments",
    "attributes": {
      "body": "blah blah blah"
    },
    "relationships": {
      "article": {
        "data": { "type": "articles", "id": "45" }
      }
    }
  }
}

or better yet:

POST /articles/45/relationships/comments HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": [
    { 
      "type": "comments", 
      "attributes": {
        "body": "blah blah blah"
      } 
    }
  ]
}

Upvotes: 16

Views: 2697

Answers (2)

xavier
xavier

Reputation: 877

Yes it is a poor example - it is listed under the "Updating To-Many Relationships" section and assumes the comment already exists. In real life your second example would be fine.

There is a notion of a client generated id that is passed alongside data, but that assumes the client is capable of producing a globally unique id, which in the case of comments, a client is certainly not.

A server MAY accept a client-generated ID along with a request to create a resource. An ID MUST be specified with an id key, the value of which MUST be a universally unique identifier. The client SHOULD use a properly generated and formatted UUID as described in RFC 4122 [RFC4122].

Upvotes: 0

Judah Meek
Judah Meek

Reputation: 598

According to JSONAPI's guide on creating resources, the following resource creation request, which looks very similar to OP's first suggestion, is a valid request.

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" }
      }
    }
  }
}

Upvotes: 2

Related Questions