HTTP Status-code for empty response and response not found - rest

We are implementing a REST based web service and we have some queries on some of the use cases.
Consider there is a unique account which contains some information (Ex. added to cart information)
What response code should we return if no cart information exists (Ex. 0).
Our understanding was to return 200 with empty response.
User added cart information to his account, but cart is removed by admin.
What HTTP statuscode shall be used?

For situation 1 there are two options:
The cart is empty. I would return 200 OK returning an empty collection.
The cart doesn't exist. The correct case for this is 404.
For situation 2, it's really the same. The only potential difference is that if you returned 404 for situation 1, you could choose 410 gone, as it indicates that a cart was here before, but it's now gone.
Regardless of which you choose, I would recommend you take the same strategy for both situations. E.g.: Either return a 2xx code for both or a 4xx code for both.
If the admin deleted the cart by doing a DELETE request, then the 404/410 status codes are more appropriate.

See This Blog. It explains it very well.
Summary of the blog's comments on 204:
204 No Content is not terribly useful as a response code for a
browser (although according to the HTTP spec browsers do need to
understand it as a 'don't change the view' response code).
204 No Content is however, very useful for ajax web services which may want to indicate success without having to return
something. (Especially in cases like DELETE or POSTs that don't
require feedback).
The answer, therefore, to your question is use 404 in your case. 204 is a specialized reponse code that you shouldn't often return to a browser in response to a GET.
The other response codes are even less appropriate than 204 and 404.
200 should be returned with the body of whatever you successfully fetched. Not appropriate when the entity you're fetching doesn't exist.
202 is used when the server has begun work on an object but the object isn't fully ready yet. Certainly not the case here. You haven't begun, nor will you begin, construction of user 9 in response to a GET request. That breaks all sorts of rules.
400 is used in response to a poorly formatted HTTP request (for instance malformed http headers, incorrectly ordered segments, etc). This will almost certainly be handled by whatever framework you're using. You shouldn't have to deal with this unless you're writing your own server from scratch. Edit: Newer RFCs now allow for 400 to be used for semantically invalid requests.
Wikipedia's description of the HTTP status codes are particularly helpful. You can also see the definitions in the HTTP/1.1 RFC2616 document at www.w3.org

Related

Http Status for partial response in the case where API makes calls to multiple APIs

I have an API whose job is to aggregate resources obtained by calling multiple other APIs and then give out the aggregated response to the client. Currently even if one or more dependent API calls fail, I go ahead and aggregate response from the other dependent APIs and then give them out to the client with a 2xx status. In case all of the dependent API calls fail, I still give out a 2xx with empty list.
In case one or more dependent API calls fail, I want to give out an indication to the client. I was thinking of using the HTTP code 206. What would be the best approach to handle this scenario. Is giving out a 206 with the names of the dependent services that failed to give out a 2xx as part of a header the correct approach. If yes, what should this header be called?
I was thinking of using the HTTP code 206.
I can't promise, but that seems like a very bad idea; see RFC 7233
The 206 (Partial Content) status code indicates that the server is successfully fulfilling a range request
If the client didn't send you a range request (see RFC 7233 for the specifics), then I don't think there is any benefit in answering as if it had. General-purpose components are likely to get confused.
As for what status code to use instead: the response code, like the headers, is meta data so that general purpose components can understand what is going on and provide intelligent assistance. The details of what you are doing, that are to be understood by the bespoke client, belong in the response body.
(Analogy - on the web, the status code and the headers are for the (general purpose) browser. The response body is for the human being.)
200 OK is probably what you want to be using here; with a "representation of the status of the action" in the payload.

HTTP response always return response code 200 even request fail, and return status code is part of REST

I recently joined a new project. In this project, all APIs in service always return status code 200. Even, if that response was should be 400 or 404, the API returns status code 200.
I asked the reason why APIs don't return other response codes, and programmers told me they don't use response code. they put information in the body.
for example, there are some missing required fields, they return response status code 200, but the body returns like this
{"result" : "fail"}
if an unauthorized user tries to access, the status code is 200, the body returns like this
{"result" : "unautherized"}
what I did before was very different, I always specified status code by cases and try to return suitable status code and message. I thought that this is the part of the HTTP protocol. However, they told me specifiying status code like 400, 404, 300, is part of RESTful API, and returning always 200 is the right status code because the server responded and it is alive. APIs, always have to return 200 except 500. Because when the server dies, it can't return anything.
So these are the question.
The server should always return status code 200 except the server dies?
Specifying various status code is the part of REST API?
Not using status code is common?
The server should always return status code 200 except the server dies?
I asked the same on Software Engineering a few years ago: Do web applications use HTTP as a transport layer, or do they count as an integral part of the HTTP server?. See also Should I use HTTP status codes to describe application level events.
Specifying various status code is the part of REST API?
No, REST is transport-agnostic. It can be used on top of HTTP, but doesn't need to. Therefore it doesn't say anything about status codes.
Not using status code is common?
Depends on who you ask.
It's a matter of preference. I extremely dislike "What is the most appropriate status code for scenario X?" questions. Also, there's:
HTTP Status Codes
HTTP Response Status Codes – REST API Tutorial
And plenty of others. I remember there being a site offering a flowchart for determining the (most) appropriate status code.
In general, don't bother. Consistency and thorough documentation is more important than assigning the appropriate number.
I've joined a project that uses exactly the same strategy -- embed status message inside the response body, and leave status code to be always 200. For consistency reason, it is better to follow existed strategy during the software maintenance time. However, it is not recommended for any new project, with reasons listed below:
"Specifying status code like 400, 404, 300" follows the RESTful design, but it is NOT part of REST. Actually, usage of 302 (redirect), 401 (Basic and Digest authentication), 404 (default not-found page in web server), 500 (default server error page) is popular decades ago, long before RESTful API these days (I know RESTful is proposed decades ago, but it is only popular in recent years).
"Returning always 200 is the right status code because the server responded and it is alive". This is incorrect. If it is, then only 200 can be used for status code -- as long as server is "alive", it can return message. 500 is not acceptable either, as in that case, server is still "alive", it does not die... Then, as the status code should always be 200, why do we need the code?
"Not using status code is common?". Actually, it is opposite. As RESTful API design scheme is more and more popular, more projects are using HTTP status code to deliver message semantics. But anyway, this is an opinion-based viewpoint.
What the team is doing may be completely appropriate for the circumstances that they are in. But labeling those patterns as REST sounds inaccurate.
I say this, because it sounds like the team hasn't given any thought to how their current messaging scheme works with generic participants in the message exchange.
For instance, caching is an important concern in the REST architectural style. In HTTP, RFC 7234 describes the caching semantics. In particular, there's a section on how cache invalidation is triggered by status codes. This in turn says that, if you aren't distinguishing between the status codes in successful and unsuccessful cases, then the generic components are going to be invalidating cached entries which shouldn't be invalidated.

Appropriate HTTP status for a PUTting a read-only entity

What is the appropriate HTTP response code when a client tries to PUT to an entity that is currently read only by nature?
A toy example is a product shipment. Before the shipment is sent, the details (address, products, quantities) can be changed (e.g. with a PUT request). However, as soon as the shipment is sent, any PUT should fail, even if the request format and syntax are correct.
It's possible that the client doesn't know that the shipment has been sent, so it's not a "careless" error on the client side.
400 doesn't seem appropriate, because the input is well formed and the syntax is correct.
405 seems like a good fit. Is this a common response in this case?
403 seems to imply authorization has been revoked, which could be misleading.
422 seems to fit well, but its use seems discouraged if you don't provide WebDAV capabilities (which we don't).
500 makes it sound like someone tripped over a cable, though I hear some developers/frameworks use this status in this case.
Is there a standard practice for this case? What is least likely to cause confusion for the API user (developer) and the end user (person using the UI)?
I would look at 405 Method Not Allowed. It is defined like this:
The 405 (Method Not Allowed) status code indicates that the method
received in the request-line is known by the origin server but not
supported by the target resource. The origin server MUST generate an
Allow header field in a 405 response containing a list of the target
resource's currently supported methods.
Your server understands the request perfectly, but it no longer supports writing. In addition, the requirement to return the client the list of supported methods sounds clean.
As an added bonus, the 405 response is cacheable by default, which could make sense in your case.
Another viable alternative is 409 Conflict:
The 409 (Conflict) status code indicates that the request could not be
completed due to a conflict with the current state of the target
resource.
Arguably the order changed state, in such a way modifying it is no longer possible. Note however that:
This code is used in situations where the user might be
able to resolve the conflict and resubmit the request.
…so I would tend toward the other one.

RESTful - What should a DELETE response body contain

Let's say I have an API where you can get users:
GET /RESTAPI/user/
And you can delete users by:
DELETE /RESTAPI/user/123
What is the RESTful convention on what the DELETE's response body should contain?
I expected it should be the new list of all users which now doesn't contain the user with id 123 anymore.
Googling around didn't get me any satisfying answers. I only found opinions on how to do that, but isn't there a strict definition of RESTful Services?
This is NOT a duplicate of What should a RESTful API POST/DELETE return in the body? and What REST PUT/POST/DELETE calls should return by a convention?
since this questions asks for a strict definition regarding DELETE. Those questions were answered by loose opinions only.
The reason you get no hard answers is because there is no hard RESTful standard. So I can only suggest that you create a hard standard and stick to it within your own APIs
I used this as a guide for RESTful services http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
It says respond with a 204 status and an empty body
I stick to those standards and document them well for anyone who wants to use my APIs
What is the RESTful convention on what the DELETE's response body should contain?
REST is an architectural style defined by Fielding in the chapter 5 of his dissertation and it describes a set of contraints for applications built with this architecture. REST is designed to be protocol indenpendent but the chapter 6 of the same dissertation describes how REST is applied over HTTP.
Once your REST application is designed on the top of the HTTP protocol, you should be aware of the HTTP semantics. And the semantis of the HTTP/1.1 protocol are currently described in the RFC 7231.
The response payload of a DELETE request that has succeeded may:
Be empty or;
Include a representation of the status of the action.
And the following response status codes are suitable for a DELETE request that has succeeded:
202: The request has been accepted for processing, but the processing has not been completed.
204: The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
200: The request has succeeded and the request payload includes a representation of the status of the action.
See the following quote from the RFC 7231:
If a DELETE method is successfully applied, the origin server SHOULD
send a 202 (Accepted) status code if the action will likely succeed
but has not yet been enacted, a 204 (No Content) status code if the
action has been enacted and no further information is to be supplied,
or a 200 (OK) status code if the action has been enacted and the
response message includes a representation describing the status.
204 No Content is a popular response for DELETE and occasionally PUT as well.
However, if you are implementing HATEOAS, returning a 200 OK with links to follow may be more ideal. This is because a HATEOAS REST API provides context to the client. Think of the location a user application navigates to after successfully issuing a delete command. Here is a brief article excerpt with more discussion on this. See the blog article for a more complete discussion.
Article: http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/
Avoid 204 responses if you're building a HATEOAS application.
This is a lesson about REST API design that I learned while building non-trivial REST APIs. In order to be as supportive of the client as possible, a REST API should not return 204 (No Content) responses.
From the service's perspective, a 204 (No Content) response may be a perfectly valid response to a POST, PUT or DELETE request. Particularly, for a DELETE request it seems very appropriate, because what else can you say?
However, from the perspective of a proper HATEOAS-aware client, a 204 response is problematic because there are no links to follow. When hypermedia acts as the engine of application state, when there are no links, there's no state. In other words, a 204 response throws away all application state.
This article covers POST, PUT, DELETE and GET. Here's the specific discussion on DELETE:
Responding to DELETE requests
A DELETE request represents the intent to delete a resource. Thus, if the service successfully handles a DELETE request, what else can it do than returning a 204 (No Content)? After all, the resource has just been removed.
A resource is often a member of a collection, or otherwise 'owned' by a container. As an example, http://foo.ploeh.dk/api/tags/rock represents a "rock" tag, but another way of looking at it is that the /rock resource is contained within the tags container (which is itself a resource). This should be familiar to Atom Pub users.
Imagine that you want to delete the http://foo.ploeh.dk/api/tags/rock resource. In order to accomplish that goal, you issue a DELETE request against it. If all your client gets back is a 204 (No Content), it's just lost its context. Where does it go from there? Unless you keep state on the client, you don't know where you came from.
Instead of returning 204 (No Content), the API should be helpful and suggest places to go. In this example I think one obvious link to provide is to http://foo.ploeh.dk/api/tags - the container from which the client just deleted a resource. Perhaps the client wishes to delete more resources, so that would be a helpful link.

400 vs 422 response to POST that references an unknown entity

I'm trying to figure out what the correct status code to return on different scenarios with a "rest-like" API that I'm working on.
This example is borrowed from another question about syntax type issues in the body, but my question assumes valid syntax throughout.
Let's say I have an endpoint that allows POST'ing purchases in JSON format. It looks like this:
{
"account_number": 45645511,
"upc": "00490000486",
"price": 1.00,
"tax": 0.08
}
What is the appropriate status code if:
the account number does not exist
the account is closed or the
account identified is not the right kind of account
These are all firmly business layer issues that prevent "processing" from occuring, however, one scenario involves something that in a GET would be a 404.
Note that the account number is not in the URL, so is 404 misleading?
Let's take these one at a time. Each of these codes is a signal to your client that the server is functioning correctly, and that something must be changed in the request before it can be successfully carried out.
HTTP 400
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
400 typically indicates a syntax error; as a user, I should look at the structure of the request before trying again.
HTTP 404
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
404 is the standard code used when a web server can't match a url path to anything. As a client, I should look at the URL of the request before trying again.
HTTP 422
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
422 is generally used for content violations. As a user, I should look at the content of my request before trying again.
Now in your case, account number is an identifying number, but is not included in the URL. A 404 would signal to your user that the URL is wrong, not the payload. Stated another way, suppose your url is:
http://www.myservice.net/endpoint
A 404 would indicate to me that no service exists at /endpoint, instead of no account number. No matter what content I submit, the server will not process my request. The fix I should make then would be to look for an error in the URL, instead of the data payload. So to me a 422 would point me in the right direction, unless you begin to include the account number in the URL.
Ultimately these are design preferences, just make sure you communicate them clearly to your users.
If you consider the accounts to be part of the state of the resource (though indirectly) then you might also consider 409 since that state is in conflict with the semantics of the request.
However, 422 is gaining popularity via Ruby on Rails and Dropwizard where it is used to indicate non-syntactic issues with the body. That growing tendency represents a strong signal to a developer using the API that they need to exclude syntax and focus on the body. Developer time is usually the single largest cost your customers will ever incur, so by directing the attention of their developers you will keep them happy.
So 409 is a possible answer, though rather novel, and 422 is the more conventional approach, although obviously RoR and DropWizard are both rather new so these conventions can be said to be changing fast!
I'd say 422 is adequate in your case, but 400 isn't bad if it's consistent with the rest of your API. It's a common convention to use 400 as an umbrella error code when there's something wrong on the client side, but either the error doesn't fit a particular error code, or you don't want to use too many of them.
A 404 is definitely wrong if there's something wrong with the POST payload.
Case 1 : Account number doesn't exist.
This is a standard case for 404.
Case 2 : Account is closed.
This has do with the logic if you keep the account details when you close it.
If you donot keep the account details when the account is closed, you can give 404.
If you keep the account details after it is closed, you must be marking it (like raising some flag) (or whatever logic you have). In this case, Status code 400 with a proper message of why it is failed and possibly remediation will do.
Case 3 : Account identified is not the right kind of account.
403, as the account is not authorised for completing any purchases makes sense to me. If there is no concept like authorised account, 400 with a explanatory message will do. But I would insist to go with 403 in this case.
Actually, in this case 404 sounds good to me.