Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json-api

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"
      } 
    }
  ]
}
like image 532
David Avatar asked Aug 13 '15 19:08

David


1 Answers

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" }
      }
    }
  }
}
like image 99
Judah Meek Avatar answered Oct 04 '22 20:10

Judah Meek