12

Why is the self and related references different in the below JSONAPI resource? Aren't they pointing to the same resource? What is the difference between going to /articles/1/relationships/tags and /articles/1/tags?

{
  "links": {
    "self": "/articles/1/relationships/tags",
    "related": "/articles/1/tags"
  },
  "data": [
    { "type": "tags", "id": "2" },
    { "type": "tags", "id": "3" }
  ]
}
4

2 回答 2

13

You can read about that here: https://github.com/json-api/json-api/issues/508.

Basically, with /articles/1/relationships/tags response will be object which represents relationship between articles and tags. The response could be something like this (what you put in your question):

{
  "links": {
    "self": "/articles/1/relationships/tags",
    "related": "/articles/1/tags"
  },
  "data": [
    { "type": "tags", "id": "2" },
    { "type": "tags", "id": "3" }
  ]
}

This response gives only the necessary data (in primary data attribute - data) to manipulate the relationship and not resources connected with relationship. That being said, you'll call /articles/1/relationships/tags if you want to create new relationship, add a new tag (basically updating relationship) to article, read which tags belong to article (you only need identity to search them on server) or delete article tags.

On the other hand, calling /articles/1/tags will respond with tags as primary data with all the other properties that they have (articles, relationships, links, and other top-level attributes such include, emphasized text, links and/or jsonapi).

于 2015-10-09T12:18:05.833 回答
3

They are different. Here is an example from my project.

Try Get http://localhost:3000/phone-numbers/1/relationships/contact you will get response like this:

{
  "links": {
    "self": "http://localhost:3000/phone-numbers/1/relationships/contact",
    "related": "http://localhost:3000/phone-numbers/1/contact"
  },
  "data": {
    "type": "contacts",
    "id": "1"
  }
}

You didn't get the attributes and relationships which is probably you want to retrieve.

Then Try Get http://localhost:3000/phone-numbers/1/contact you will get response like this:

{
  "data": {
    "id": "1",
    "type": "contacts",
    "links": {
      "self": "http://localhost:3000/contacts/1"
    },
    "attributes": {
      "name-first": "John",
      "name-last": "Doe",
      "email": "john.doe@boring.test",
      "twitter": null
    },
    "relationships": {
      "phone-numbers": {
        "links": {
          "self": "http://localhost:3000/contacts/1/relationships/phone-numbers",
          "related": "http://localhost:3000/contacts/1/phone-numbers"
        }
      }
    }
  }
}

You can see you retrieved all the information you want, including the attributes and relationships.

But you should know that relationships can be used for some purpose. Please read http://jsonapi.org/format/#crud-updating-to-one-relationships as a sample.

于 2017-04-20T10:06:43.097 回答