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

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.

Related

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.

HTTP Status-code for empty response and response not found

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

Why HTTP Rest has different methods like GET, PUT, POST instead of just one or no method at all?

Why do we have different methods for HTTP request. GET can not send data(body) and can only request something only through URL params. Put is like changing a field value on the server and Post performs an operation everytime we execute it (concept of Idempotence).
Why can't there be one method or no method at all ?
Why can't there be just a simple HTTP request where we can send data if we want. Now it depends on server logic how it wants to process that request based on the request content (data / body). If the server wants to just execute it like a get request & return something or perform an operation like a POST request & return something. It would have been more simpler.
Why can't there be just a simple HTTP request where we can send data if we want
Because that's not how HTTP works. Each HTTP request has a required request method.
REST leverages this by reusing the semantics of the methods.
Why can't there be one method or no method at all ? Why can't there be just a simple HTTP request where we can send data if we want.
Because describing the semantics of the messages in a consistent way allows generic components to participate in a meaningful way.
For instance, the semantics of a given request are constrained by the common method properties; if the metadata of the message describes itself as idempotent, then generic participants know that, in the event that a response is lost, they can simply repeat the message.
Likewise, if a message is known to be safe, then each of the components know that the message can be dispatched speculatively -- allowing caches to prefetch representations that you may need, communicating to spiders that the content is safe for retrieval and so on.
The HTTP methods support finer grains of distinction; GET vs HEAD, PUT vs DELETE, POST vs PATCH. And of course there are extensions that support other semantics as well.
From the perspective of REST, it doesn't have to be a method per se, so long as the semantics are expressed in such a way that generic components can act on it. HTTP happens to have used methods.
The request method token is the primary source of request semantics; it indicates the purpose for which the client has made this request and what is expected by the client as a successful result.
You are absolutely right that no method at all would be much simpler. But it would also be a lot less powerful: you lose the ability to leverage generic components (like web browsers, caching proxies). The metadata constraints are what make the web possible.
It's all about the semantics of the request. From the RFC 7231:
The request method token is the primary source of request semantics;
it indicates the purpose for which the client has made this request
and what is expected by the client as a successful result.
Here's a brief description of some HTTP methods defined in the RFC 7231 (click the links to check the full method definition):
GET: Transfer a current representation of the target resource.
HEAD: Same as GET, but only transfer the status line and header section.
POST: Perform resource-specific processing on the request payload.
PUT: Replace all current representations of the target resource with the request payload.
DELETE: Remove all current representations of the target resource

HTTP Error Code 406

I understand that correct use of HTTP Status codes is a good indicator of correct RESTful implementation of a service. I'm not sure what code to return when the following resource is called with an invalid token to confirm creation of a new user account:
/user/confirmation POST {param is confirmation token}
By best guess is 406 Not Acceptable? But maybe it's a 200 because there is no error as such in which case the response much include information to indicate a failed confirmation?
Both 406 and 200 are unsuitable for this situation:
406 is meant for content negotiation, when the server cannot send a representation of a particular resource with the media type indicated in the Accept header of the request.
200 must be used when the operation has succeeded, what's not the case.
You could probably go for the generic 400 to express a bad request or go for 403 to indicate that the request is forbidden.
Sending the right status code is as important as proving a payload that describes the problem and helps your client to determine the cause of the error.
For reporting problems in your HTTP API, I advise you to have a look at the RFC 7807: it defines simple JSON and XML document formats to inform the client about a problem in a HTTP API and also defines the application/problem+json and application/problem+xml media types.
Michael Kropat put together a pretty useful set of diagrams to determine the most suitable status code for each situation. See the following diagram for 4xx status codes:

Best way to return error messages on REST services?

I've been looking at examples of REST API's like Netflix http://developer.netflix.com/docs/REST_API_Reference#0_59705 and Twitter and they seem to place error messages in the statusText header response instead of the responseText. We're developing an internal RESTful api and I am arguing for sending custom statusText messages and ignoring the responseText.
For the scope of our app, we're returning error 400 when the user has tried doing something they aren't supposed to, and the only error messages that will be updated in the UI for the user will be delivered with 400. I am of the belief that the message should be sent as a modified statusText but one of the engineers (who knows a bit less about REST than me) is arguing for sending it in the responseText.
What's the best way to go?
HTTP defines that you should put a descriptive error message in the response entity body, aka responseText.
statusText is not rendered or processed by any client.
I'd use the status text for the error message type, aka 400 Client Error, and the body for a description of the problem that can be rendered to the user, in whatever the format the client may be able to process.
Edit: Note that since then, a new standardised format exists to communicate in a standard fashion error details back to the client, which you can find at https://www.rfc-editor.org/rfc/rfc7807 and which I would recommend.
I think you're right, the general approach is use the existing error mechanism built into HTTP.
In general, try to map your errors to existing HTTP errors, for example if they request something they don't have permission to, return a 403 error.
If they request something that doesn't exist, return a 404.
Alex
According to the HTTP specification (rfc2616): "HTTP status codes are extensible"
However I don't think that creating new statuses for every different error message is the correct approach:
I would say choose HTTP Status appropriately (HTTP Status Code Definitions) if you can't find any category which matches your requirement create a custom one (but I'm sure you will) and put error messages in the HTTP response body.
Picking appropriate status code for your responses is extremely important as it is a key enabler of self-descriptive messages.
The entity body should be a representation of the resource's state and ideally contain hyperlinks to available next states in your application
Http Status Codes are pretty self explanatory and should be used as such. Returning 200 OK with validation errors is pretty Soap-y and misleading. Any REST Client implementation 4xx and 5xx errors go into a error block and it really depends on case to case basis if you really want to use the response body for non 2xx responses.