What is the expected error code if a route can't be created? - rest

I am using the REST version of the Here Maps API. It seems that if I provide a destination location (latitude, longitude) that cannot be routed the API is returning a HTTP Error of 400 (Bad Request).
I was under the impression I would get a 200 response code but no data would be returned.
For example if I send a request to the API with New York as the source and Paris, France as the destination the API returns a 400 bad request.

The response codes of RESTful APIs are determined by the API developers. From what you are saying it seems that Here Maps does not know how to route someone over the Atlantic Ocean and is telling you that by returning a 400 Bad Request response instead of providing a 200 response. Http Status Code Explanations
You'll want to dig into the api documentation, perhaps the API is expecting two points that can be routed by land and you can supply a way to indicate that by-air and/or by-sea routes are okay also.
Alternatively, you will need check the response status from the Here Maps API first on your program before you attempt to consume it as a 200 status and if you receive a 400 status then you can communicate that there was an error to your end user which you could inform them of the reasons why a particular request might fail. Such a source and destination on continents not linked by a land mass.
(This reminds me of how Google Maps used to provide driving directions which would tell you to kayak across oceans, not sure if still does that but illustrates a way to resolve a by-land route that cannot be taken only by land.)

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.

what should be the appropriate http status code for POST API request when trying to create resources beyond maximum limit

I searched almost 2-3 hours for proper response code for below POST API but i did not get proper answer so I kindly request someone to help me here.
We have a POST API which creates resources maximum 10 times.
When we call POST API for 11th time, we should get a response with message "User exceeded the limit to create resource" and proper response code.
Please suggest what should be the proper response code.
With the level of details provided in your question, I would suggest a status code in the 4xx range, along with a response payload that describes the error in a meaningful way for the client.
You could consider 403 (Fobidden), expressing that the server understands the request, but refuses to authorize it. However there might be other status codes more suitable for your situation, depending on what your are trying to achieve:
402 (Payment Required): If the quota of requests has been exceeded, but more requests could be performed upon a payment, you could consider the 402 status code (even though the documentation says it's reserved for future use, its reason phrase is pretty clear and defines well its purpose).
429 (Too Many Requests): If you are applying restrictions on the number of requests per hour/day, the 429 status code may be suitable for your needs. However this status code is used by a server to indicate that too many requests have been received in a short amount of time, that is, the client is throttling.
If these status codes don't seem to match, simply go for 400, which expresses a bad request.
Status codes indicate the result of the attempt to understand and satisfy the request.
But you have to keep in mind that status codes are sometimes not sufficient to convey enough information about an error to be helpful. That's why you are advised to return a payload that describes the error. The RFC 7807 defines a standard for that.
If you create your own status code for that (what you could do, but doesn't mean you should do), be aware that clients will treat unrecognized status codes as being equivalent to the x00 status code of that class. From the RFC RFC 7231:
For example, if an unrecognized status code of 471 is received by a client, the client can assume that there was something wrong with its request and treat the response as if it had received a 400 (Bad Request) status code. The response message will usually contain a representation that explains the status.
You should try to use a 4xx status. Personally, I would use 403 because the user is forbidden to create the object.
The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it. This status is similar to 401, but in this case, re-authenticating will make no difference. The access is permanently forbidden and tied to the application logic, such as insufficient rights to a resource.
source
And then you can add a message to the request body explaining why the request is not successful. Some more info about 403
Also, I like to check this page if I need an overview of all status codes: Status Codes
I would suggest 400, Bad Request.
403 is more for authorization issues which this is not.
Provide a clear explanation why you're returning 400 and you're good to go.
Yes, it's a more generic solution, which is exactly what makes it more appropriate.
HTTP status codes have very clear use cases which are understood by everyone. It is not advisable to "reuse" one for something else.

What status code to use when a parameter is missing in the query string?

I have an endpoint that requires a parameter passed via the query string (is a GET verb).
What is the appropriated status code to give when this parameter is missing from the request? 400 is the one? or should I respond with a 404?
[GET /search?q=ok] => 200 OK
[GET /search] => 400 Bad Request? or 404 Not Found? Or 422 Unprocessable Entity? Others?
TLDR It's an HTTP 400 - Bad Request.
It's a 400 because the user did not send the Required input field.
why not 422 - because this case fits to 400. Keeping your consumers in mind, you shouldn't go to non-popular response codes if you don't really need to.
Cases for HTTP 404:
Url which the client requested is not existing in your server (usually this will be handled by your server. Application developer usually doesn't have to do anything unless you want a nice looking 404 page or for SEO reasons).
If it was a path parameter and client was looking for an entity with an id (for Example (/students/{id} and your application couldn't find such entity, you may respond with an HTTP 404.
Let's say, user send the query parameter and you did not find any items matching the query param, make no mistake, it's still an HTTP 200 with body as an empty array or so (not a 404 unlike mentioned in the previous case). Example: /customers?lastname=unobtanium
It should be 400 - Bad Request.
The request could not be understood by the server due to malformed
syntax. The client SHOULD NOT repeat the request without
modifications.
404 - Not Found
The HTTP 404 Not Found Error means that the webpage you were trying to
reach could not be found on the server. It is a Client-side Error
which means that either the page has been removed or moved and the URL
was not changed accordingly, or that you typed in the URL incorrectly.
Its means server is not able to find the URI you specified. but in your case URI is valid but parameters are missing so 400 is right way to do it.
What is the appropriated status code to give when this parameter is missing from the request? 400 is the one? or should I respond with a 404?
I would argue that 404 is appropriate
The 404 (Not Found) status code indicates that the origin server did
not find a current representation for the target resource or is not
willing to disclose that one exists.
The fact that your routing implementation happens to send /search and /search?q=ok to the same handler does not mean that they are the same resource. /search identifies a resource, there's no current representation available for it, so you send a response back to the consumer explaining the problem, and put 404 in the meta data.
The big hint in the spec is this one:
A 404 response is cacheable by default
That lets us inform the client (and any intermediary components) know that this response can be reused.
It's a useful property, and it doesn't apply (out of the box) to 400 Bad Request
Heuristic: your web api should act like a document store. If you ask a document store to give you a document, but you spell the key wrong, what do you get? Some flavor of KeyNotFound exception. Same thing you would get if you asked a web server for a document in your home directory, but your spelled the file name incorrectly.
The semantics of the response indicate the right status code to use, not the implementation details.

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.