Which HTTP code to use for an empty subresource in a REST API? - rest

Let's say I've a resource articles at /articles.
These articles may have related articles, so I fetch them by GETting /articles/{id}/related.
What should I return is there is no related articles?
I can think of:
404 Not Found, maybe with an empty collection
204 No Content
200 Found with an empty collection
Any advices? (please give arguments)
By the way, it may applies to pagination. If I request page 3 of 2, then the page 3 will return an empty set, should It be a 404?

404 is not what you are looking for. It's an error condition. Your case is not an error. The client currently doesn't know if there are any related articles and wants to know. That is not an error.
204 is not appropriate either. RFC 2616 states:
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
204 doesn't specify that there are no related articles. It just says that the server doesn't need to send the data.
200 with empty collection on the other hand would satisfy your need.

I wouldn't use 404 -- that would tell the client it "I'm unable to tell you whether there are any releated articles". It would be appropriate if the {id} given is not recognized at all. What you want is a positive response to tell the client, yes, good question, and here is the (empty) list of related articles.
204 is not good either, for related reasons. It specified that there is no answer, which is still different from an answer that is there but happens to be the empty list. Its description makes more sense for a POST than for a GET.
200 with an empty list is just right.

Return 200 with an empty array.

Related

Correct HTTP status code for possible absent entity: 200 or 204 or 404

I've searched a lot about this and have found different answers, also, my case is a little different.
The context:
I have a document A with a possible sender S
Server X (so not a browser) requests the sender from document A on Server Y, but the sender is absent.
What should server Y return:
200: with a null object (not really OK and dangerous for nullpointers on Server X)
204: a correct status I think, but this is mainly used when the endpoint does not return data in general (e.g. post, update, delete), which can be confusing
404: this should definitely the answer for .../sender/{sender_id}. But in this case we ask the sender of a document, and no sender is a correct answer...
So, what would be the best practice, or is there another approach which is better fitting for this.
Thanks in advance!
Broad rule: don't try to make status codes specific the details of your api or your domain model. Those are messages to generic components (like browsers, caches, proxies) that don't need to know anything about the specifics of your domain model and your integration protocol.
404: this should definitely the answer for .../sender/{sender_id}. But in this case we ask the sender of a document, and no sender is a correct answer...
The 4xx class of response codes indicate an error in the client request. In other words, the client asked the question wrong. 404 specifically implies that the client addressed the request to the wrong integration resource.
So it's not what you are looking for.
204: a correct status I think, but this is mainly used when the endpoint does not return data in general (e.g. post, update, delete), which can be confusing
204 has a very specific meaning - is says that the representation provided in the response is zero bytes long. "You asked me to send you the contents of this file, and I'm successfully doing so, but by the way the file is empty."
So if the representation of an absent sender is zero bytes long, aces! But if the representation is instead an empty json object
{}
Then 204 is off the table.
200 is probably your best bet.
I would suggest 404 Not Found matches best what you describe as "sender is absent"
Just in case here you can see a list of status codes: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
There are two cases here.
If you are requesting a collection eg: /users and there are no users available on the server then your service should return 200 OK with an empty list.
If you are requesting a resource by id eg: /users/id and if the user is not available then you should return 404 NOT Found as the user id that you are searching is not available on the server.
Based on your situation(assuming you are requesting for a collection of resources), I probably recommend returning 200 OK with the empty list. If you does not have control over the server then you may need to have a null check on the client side.

Rest service returns 404

What is the best practice in return codes if a call to a rest service executes a database query, no results are found and it returns.
Should this be a 404 or a 200 with a message stating no records?
The URL has resolved correctly and no server error has occurred just that there are no records returned.
EDIT:
Example url is:
http://localhost/app/pr_xyz/1234
Used to retrieve a list of xyz that belong to the existing user 1234. The user id 1234 has already been retrieved and is known to exist in the database. This URL (pr_xyz) is just to retrieve a list of xyz that belong to that user.
The relationship is 1 user to 0 or many xyz.
In this case the existing user has no xyz. Should this be a 404 or 200 with meaningful message.
Also I have no control over the URL.
Agree with #Satya, it should be a 200, but we can arrive at the answer by working backwards.
So, we start with the full list of HTTP status codes.. Start from the bottom.
Is it a server error? No? Then it's not a 5xx
Is it a client error? Maybe? Perhaps it's not a 4xx
It's obviously not a redirect, so it's not a 3xx.
Is it a successful call? Perhaps.
Are you returning a provisional response? No, it's not a 1xx either.
So by process of elimination, which are looking at the 2xx codes. Exactly which would be a good fit depends on the semantics of your application.
Since, this is not a DELETE call, then I probably wouldn't use 204 No Content, which is probably the only good alternative. It's not that there's no content.
There is content: "0 results found". Google doesn't show you a blank page when there are no search results.
So we arrive at 200, as well as returning a meaningful body. If you were returning raw results, then you might want to consider wrapping them in a search-results object to provide some meta-data.
Ah! So wait, what if instead of search results, you are indicating a collection of RESTful resources?
GET /items
In this case, I would still return a 200 with a body that says there are no items.
What if, you were trying to retrieve a particular resource?
GET /items/1234
In this case, yes, you want to imply that item 1234 does not exist, and you should return a 404.

HTTP 200 or 404 for empty list?

I know this is a fairly common question, but I haven't found an answer that satisfies me.
I've been using django rest framework for a while now, but this is mostly irrelevant other than the example given. Its default behaviour is to return an HTTP 200 with an empty list resource when accessing a route with an empty list of items.
E.g.: if we had a route such as /articles/ to access a list of articles but it contained no items we would get a response like the following json:
{"count":0, "next":null, "previous":null, "items": []}
Which is perfectly fine. We found the resource we were looking for at /articles/, it just happens to have no items in it.
If we access the route /articles/?page=1, we get the exact same response.
So far so good. Now we try to access /articles/?page=2, and the response code changes. Now get get a 404 as if the resource could not be found with an error message saying that the page contains no results. Which is the same case as with ?page=1...
I was perfectly ok with this behaviour, but today I started questioning this design. How is the ?page=1 case different than ?page=2 ? And what's more, how could you tell if the request was "valid" when issuing a HEAD request? Valid in the sense of containing any results.
This could be useful in cases like filtering a list checking the availability of a certain field (for example, issuing a HEAD request to /users/?username=ted).
A 200 response would clearly mean the request was understood and items were found.
A 404 would mean the request was understood, but no items were found at that location/URI (AFAIK the query parameters are also part of the URI)
In case the request could not be understood a 400 would be returned for syntactic errors, and a 422 for semantic errors.
Is this a good design? Why do most people seem to disagree with it and what drawbacks are there in it?
I would go for 200 because the resource is articles.
While querying for ted in users the same applies, users is the resource and as long it is there, a 200 is okay from my point of view.
If you would GET users/ted a 404 would be as good as a 410 (GONE) if a user named ted was there in the past (may better applies to articles than users).
Because we are ok with an empty page1, not ok with an empty page2.
This is driven by the UI consideration (page1 must exist!), nevertheless, it decides the response code.
This really boils down to the "null vs empty collection" argument. The cases for null are also cases for HTTP 404, and the cases for an empty collection are also cases for HTTP 200.
if we had a route such as /articles/ to access a list of articles but it contained no items
Assuming this is a global list of articles, i.e:
http://mywebsite/articles
then this response can never be null, and therefore should never be a 404. The global list of articles always exists, and therefore the collection is always not-null, regardless of whether it contains elements or not.
A simple example here is thinking of a SQL query. If a table exists, even if it's empty, a query will return a result (be it empty or not), so use 200. If the table itself does not exist, you get a query error, so 404.
But if the articles are contained within another resource, e.g. their author:
http://mywebsite/authors/johndoe/articles
Now we get to the part where null (and thus 404) is meaningfully possible.
If johndoe exists and has articles, you return a non-empty list
If johndoe exists and does not have articles, you return an empty list and HTTP status 200
If johndoe does not exist, then you return null and HTTP status 404
This communicates the correct response to the user. 200 reveals that the data was correctly fetched, whereas 404 reveals that the requested resource simply does not exist.
Note that this is slightly different when referring to a specific article instead of a list. When returning a specific resource (or not), instead of a list, 404 is the only correct HTTP status for a 'no item' response.
http://mywebsite/article/1
Here, you either return the article or null.
http://mywebsite/authors/johndoe/articles/1
Here, you return 404 when either author johndoe or article 1 does not exist.
200 simply means the request has succeeded. The information returned with the response is dependent on the method used in the request, for example:
GET an entity corresponding to the requested resource is sent in the response;
HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;
POST an entity describing or containing the result of the action;
TRACE an entity containing the request message as received by the end server.
404 - The server has not found anything matching the Request-URI - In this case I think it means we did not find the page that articles would have been listed on.
So 200 it is. - but perhaps understand what is being returned and format a message that 0 article have been returned.

REST status code 204 on paginated result

I am designing a REST like API for paginated data retrieval of a YUI-based client.
The REST URL looks like this for a GET request:
/app/catalog/data?startIndex=<int>&results=<int>&sort=<sting>&dir=<string>
All parameters are optional, i.e. if no parameters are given, all data from DB will be dumped.
Now say that there are only 1000 records in the database. Following reqeust is made:
/app/catalog/data?startIndex=1100&results=25
What status code should I return if the paginated result from the database remains empty though the request was fine?! I can't decide whether this is 204 or 404.
The produced media types are JSON and CSV.
I would say 204 is most appropriate. The request was successful, just with no results.
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
Sounds exactly like the case.
I can't decide whether this is 204 or 404.
Neither. Just return 200 with an empty result (empty XML document or JSON array, whatever you use). Typically I use REST services with paginated views so along with results page I return total number of records. This will help clients to realize the mistake. But technically it is nothing wrong.
Use 204 for DELETE operations (there's really no content to return) and for PUT.
BTW (bold mine):
if no parameters are given, all data from DB will be dumped
Believe, you don't want to do this...
What format do you normally return your results in? I'd be inclined to make this 204 or even 200 returning an empty list.
HTTP 204 in pagination response is not factible because of the payload. When paginating you should return pagination information like, items returned, total items, offset, etc. which makes no sense with HTTP 204.
HTTP 204 is useful on resource updates (ie PUT) when you want to explicitly say that the resource does not need to be fetched again (GET). For example, resources that have calculated fields and require a refresh of the view after every update, fetching those calculated fields from the server. Therefore, the 204 status code has specific use cases and must be designed and documented.
I would use one of:
HTTP 200 with count=0 and no items in the returned list.
HTTP 400 because invoker asked for an url that is invalid
HTTP 404 because items to return are not found
Choose the one that best suits the way your API works.
I think it's safe to return an error (4xx + error info) in this situation because the offset can be exceeded by one of these assumptions:
A coding error
Invoker is not fetching data from begining (no fresh state)
Invoker ignored pagination data (present on each response)
You are not using total field in the response (which is optional because there are some situations where you can not count all items or simply it's very expensive counting them). In this case, if your last page has the same number of items (count) as the number of items asked for in the request (limit), there is no way to know that this is the last page, so you try another one. In that last request you will get a count=0 in the response and you can stop asking for pages. This case makes it fair to return a 200 code also because the programmer did exactly what you asked for in the API documentation.

Should a RESTful API return 404 for arrays of objects?

Lets say there's a Product with Orders. If you ask for /products/product_id, it will return a 404 if product_id doesn't exist. But should /products/product_id/orders return a 404 if no orders exist for this product or should it return an empty array?
I would return an empty collection. A product with zero orders is a completely valid concept, so the existence of an empty orders collection makes more sense than a 404 which would infer that this product does not have a orders collection.
You really should do only one of two things
Either Return a 200 (OK) status code, and an empty array in the body.
Or Return a 204 (NO CONTENT) status code and NO response body.
To me, option 2 seems more technically correct and keeping in line with REST and HTTP principles.
However, option 1 seems more efficient for the client - because the client does not need extra logic to differentiate between two (success) status codes. Since it knows that it will always receive an array, it simply has to check for whether it got none, one, or many items and process it appropriately
Do not return arrays. Return an object in any case, like
{
offset: 30,
limit: 10,
arr: []
}
it allows you to add metadata (for pagination or smth else)
usually with http status code: 200
Also, this is conventional web API behavior, driven by security concerns:
https://cheatsheetseries.owasp.org/cheatsheets/AJAX_Security_Cheat_Sheet.html#always-return-json-with-an-object-on-the-outside
In my opinion:
We're talking http status values here, and should be of a higher level of giving responses.
One should see this in layers of delegates. Like when your api is not able to answer a request, in case the api call itself is not available, then you could reply with a 404.
But when your call exists, and it could reply with a collection of data, but its an empty collection, you could return just a http 200, with an empty result.
I would use http status values to give an indication on the request validation, and not directly make it dependent on the content in the deeper api layers.
Or one could strictly follow protocols found on the net, but nobody follows them...