Search code examples
jsonrestjson-api

Is returning only IDs for a JSON API collection allowed?


So let's say I have a resources called articles. These have a numeric id and you can access them under something such as:

GET /articles/1 for a specific article.

And let's say that returns something like:

{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!",
      "body": "A bunch of text here"
    }
  }
}

Now my question is how to handle a request to GET /articles. I.e. how to deal with the request to the collection.

You see, accessing the body of the article is slow and painful. The last thing I want this REST API to do is actually try to get all that information. Yet as far as I can tell the JSON API schema seems to assume that you can always return full resources.

Is there any "allowed" way to return just the IDs (or partial attributes, like "title") under JSON API while actively not providing the ability to get the full resource?

Something like:

GET /articles returning:

{
  "data": [
    {
      "type": "article_snubs",
      "id": 1,
      "attributes": {
         "title": "JSON:API paints my bikeshed!"
      }
    }, {
      "type": "article_snubs",
      "id": 2,
      "attributes": {
         "title": "Some second thing here"
      }
    }
  ]
}

Maybe with links to the full articles?

Basically, is this at all possible while following JSON API or a REST standard? Because there is absolutely no way that GET /articles is ever going to be returning full resources due to the associate cost of getting the data, which I do not think is a rare situation to be in.


Solution

  • As far as I understand the JSON API specification there is no requirement that an API must return all fields (attributes and relationships) of a resource by default. The only MUST statement regarding fields inclusion that I'm aware of is related to Sparse Fieldsets (fields query param):

    Sparse Fieldsets

    [...]

    If a client requests a restricted set of fields for a given resource type, an endpoint MUST NOT include additional fields in resource objects of that type in its response.

    https://jsonapi.org/format/#fetching-sparse-fieldsets

    Even so this is not forbidden by spec I would not recommend that approach. Returning only a subset of fields makes consuming your API much harder as you have to consult the documentation in order to get a list of all supported fields. It's much more within the meaning of the spec to let the client decide which information (and related resources) should be included.