Inclusion of related resources: what to do with empty results?

Let’s consider a valid and supported request to include related resources, for example, GET /posts?include=comments. Now, if we consider the case where no post has comments, what is the best (or the recommended) approach:

  1. Respond with included set to an empty array:
{
  "data": [ <some posts here> ],
  "included": []
}
  1. Respond with included set to null:
{
  "data": [ <some posts here> ],
  "included": null
}
  1. Respond without a included field:
{
  "data": [ <some posts here> ]
}

I did not find a clear answer by checking the specification, the forum, and the JSON Schema, so I created this post.

I believe option (1) to be the best. Also, option (3) seems to be the worst because the client may be lead into believe that the “include” query was ignored.

null would not produce a valid response json according to the schema: JSON:API — Frequently Asked Questions

{
  "data": [ <some posts here> ],
  "included": null
}

I think that an empty array for included when inclusion is explicit in the request is more predictable and more friendly to the consumer of the API. Omission of the included keyword when requested may generate confusion.

1 Like

In fact, while JSON:API 1.0 allows the included member to be omitted if the list is empty, JSON:API 1.1 specifically requires it to be present if an include query parameter is sent.

So returning an empty list for included is the best approach if include was specified and there’s nothing to include.

(Assuming a non-error response.)

-Fred

1 Like