Sparse fieldsets and relationships

How do you return relationships when doing a sparse fieldset query?

http://jsonapi.org/examples/

Gives the following example:

GET /articles?include=author&fields[articles]=title,body&fields[people]=name HTTP/1.1

Except the example response includes people, but the article does not have any relationships.

`
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json

{
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!",
      "body": "The shortest article. Ever."
    }
  }],
  "included": [
    {
      "type": "people",
      "id": "42",
      "attributes": {
        "name": "John"
      }
    }
  ]
}

`

This could be a problem for ordering (for example the relationships in the article could show who comes first).

How do you request the relationship info for the resources that are “included”?

For instance in this case I might only want the “people” relationships.

Hi,

Check out this post and the discussion that followed, and let me know if it doesn’t clear things up!

Ok, that helps…So what I need to do in the above example to get the relationships is:

GET /articles?include=author&fields[articles]=title,body,people&fields[people]=name HTTP/1.1

Correct?

Not quite. You’d do:

GET /articles?include=author&fields[articles]=title,body,author&fields[people]=name HTTP/1.1

Because you want to include the “author” relationship in each article. (“people” is a type name, rather than a relationship/field name.)

Breaking the request into parts:

  1. GET /articles?include=author: Give me the articles and, for each article, include it’s author resource

  2. &fields[articles]=title,body,author: (But) for resources of the the articles type, include only the title, body, and author fields.

  3. &fields[people]=name: (And) for resources of the people type (which are present in included, but could theoretically have been part of the primary data too, if you’d asked for a different collection), include only the name field.

ok, thanks for the clarification.

would
GET /articles?include=author&fields[articles]=title,body,author&fields[author]=name
work out better since you could have more relationships (for example: editor) with type people in them? I could want a different set of fields for those relationships.

It seems redundant that you would include an author and must have them listed in the fields section.
Why would I include them if I wasn’t going to use their info?

1 Like