Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API design - json_api best practice to return no data

I have Rails app that also has an API. I've been trying to follow http://jsonapi.org for the overall structure, but I can't find any guidelines for when it comes to result without any data. I for example have an endpoint that looks like this:

https://[root]/api/apps/34/localized_strings?from_date=1330776000

Where from_date is a unix timestamp, if the server have updated or newer data based on this date value I return all the data, it there a no updates I want to return no data. And I wonder what's the best way for doing this is. The current result looks like this:

{
  "data": []
}

Would it be better or more conventional based on http://jsonapi.org to instead return a status of "status": 204 in cases where there are no changes or data?

like image 343
Anders Avatar asked May 30 '16 08:05

Anders


People also ask

Should an API always return JSON?

REST APIs should accept JSON for request payload and also send responses to JSON. JSON is the standard for transferring data. Almost every networked technology can use it: JavaScript has built-in methods to encode and decode JSON either through the Fetch API or another HTTP client.

Which of the following is not a best practice for designing an API?

using api keys not a best practice for designing an API It is standard procedure for APIs to accept JSON queries as the payload and to return responses in JSON format.

What REST API should return?

The API should always return sensible HTTP status codes. API errors typically break down into 2 types: 400 series status codes for client issues & 500 series status codes for server issues. At a minimum, the API should standardize that all 400 series errors come with consumable JSON error representation.


2 Answers

Just return head :no_content, so rails will return 204 status code with empty content

Here is an example for destroy

def destroy
  # Destroy stuff

  # Return 204, no content
  head :no_content
end
like image 155
Hieu Pham Avatar answered Oct 20 '22 22:10

Hieu Pham


According to the specification, a response representing an empty collection would be:

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

{
  "links": {
    "self": "http://example.com/articles"
  },
  "data": []
}

A server MUST respond to a successful request to fetch an individual resource with a resource object or null provided as the response document’s primary data.

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

{
  "links": {
    "self": "http://example.com/articles/1/author"
  },
  "data": null
}
like image 23
Wilson Silva Avatar answered Oct 20 '22 20:10

Wilson Silva