Relevant HTTP Status code on the Rest API - rest

I have a scenario by passing invalid data in Path variable which is input to fetch the data from Database.As the provided data is not valid so it triggers "500 Internal Server Error" from the database as could not found the data.
and have customized HTTP Status as 404(NOT_FOUND) because data is not found.
Would like to understand,what can be the best HTTP Status code for this scenario other than 404?

HTTP is an application protocol, whose application domain is the transfer of documents over a network (Jim Webber, 2011). The status codes we use in the response are metadata from the domain of document transfer -- which is to say, we care about what the message means, not why our implementation is sending it.
The information specific to your domain, which communicates the details of the problem to the client, belongs in the message-body of the response. The status code is there so that generic components, that don't know the specifics of your domain, can "do the right thing" -- where the right thing is constrained by HTTP semantics.
Michael Kropat published flow charts that may help select the correct status code. Alternatively, you can look through the HTTP Status Code Registry, which has links to the standard that defines the semantics of each code.
Broadly speaking, if the problem is with the request, then we use some message from the 4xx message class; problems in the request are client errors. 404 specifically directs the client's attention to the target-uri.
So if the request is bad because information encoded into a path segment is incorrect, then 404 is the correct choice, because it tells the client where to look for the problem. The only reason that you would look elsewhere is if some other part of the 404 semantics were inappropriate for your circumstances.

Would like to understand what can be the best HTTP status code for this scenario other than 404?
If you are looking for something other than 404, then you could look into the more generic 400. From the RFC 7231:
6.5.1. 400 Bad Request
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).
But bear in mind that the 404 status code itself is suitable for this situation. See the following quote from the RFC 7231:
6.5.4. 404 Not Found
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. [...]

Related

What is the proper http response code for bad parameters

new user here.
I have a REST service which cannot work unless the parameters in the request are valid. I've looked over the list of possible HTTP response codes, and none of them seems quite right. 500 doesn't seem right, because it's actually an expected error. 404 isn't right because the ressource requested is available in principle. 406 is specific to content negotiation, which isn't what's happening here. And so on.
Is there a convention which HTTP response code to send to signify that the request is not valid for reasons of its content?
Is there a convention which HTTP response code to send to signify that the request is not valid for reasons of its content?
422 Unprocessable Content
The 422 (Unprocessable Content) status code indicates that the server
understands the content type of the request content (hence a 415
(Unsupported Media Type) status code is inappropriate), and the
syntax of the request content is correct, but was unable to process
the contained instructions. For example, this status code can be
sent if an XML request content contains well-formed (i.e.,
syntactically correct), but semantically erroneous XML instructions.
Is it OK to use that on a general HTTP request? I had considered it, but read somehwere it is specific to WebDAV.
The original definition of 422 came from WebDAV (specifically RFC-4918), but the IANA status code registry currently uses HTTP Semantics as the standard reference.
A general purpose HTTP component that doesn't recognize 422 should interpret the response as though it were a 400 Bad Request, which is fine.

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.

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:

HTTP Status 400 Validation Versus Verification

Although RFC 7231 was intended to bring clarity, it evidently has brought ambiguity regarding status code 400. Note this SO answer and the comments. One person says 400 now includes logical, application or verification errors, another person says that 400 still is intended only for syntactic or validation errors.
6.5.1. 400 Bad Request
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).
I would like to get a more definitive answer about this. Consider two scenarios where a POST or PUT attempted to provide an e-mail address:
The e-mail found in the request failed validation (e.g. it contained "hello#gmail.com"). A 400 reply is sent.
The e-mail found in the request failed verification (e.g. another user is already using that address). A ??? reply is sent.
I want to follow RFC 7231. My reading of the 6.5.1 tells me that the verification error should receive a 409 (or 422) response. But others disagree, and claim it should now be a 400.
Does anyone have more information that would resolve this ambiguity?
200 is a fine status code to send in this situation. After all, do HTML forms get a 4xx back when you don't put in a valid post code?
Status codes are for generic consumption, not application-specific semantics. They're useful when a non-specific recipient -- e.g., a proxy, a cache, a HTTP library -- can do something interesting when it comes in.
So, 400 is to be used when there are errors stemming from client problems (such as bad request HTTP syntax). It was made more generic in 7231 because x00 status codes are the most generic of their series, and should be considered fallbacks when a more specific status code isn't defined.
You can use 400 for a validation error too, and it will be theoretically, slightly helpful in that a HTTP library knows not to repeat that request -- but it certainly isn't worth getting too concerned about if it's 200.

Should POST request return 404 if reference to other entity fails?

I'm building an API which operates on a noun Foo. When a caller creates an instance of Foo with a POST request, they are required to provide an ID to a second noun, Bar. If the ID they provided is of the right type but there is no Bar with that ID, is 404 the right response?
I think it depends on whether the ID is in the URL or not. The URL is the address for a resource, if the ID is in the URL and no item with this ID exists, or you don't provide it at all, then the URL is invalid, so no resource could be found, so that's a 404.
However, if the ID is not in the URL but in the data from the POST request, and the URL is a valid address to a resource, then a 400 Bad Request should be returned.
I would suggest using HTTP 400 (Bad Request).
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1. One could interpret 400 as a generic indication that the client did not form the request correctly.
One could also make a case for returning a 500 response. If the client believes that the Bar reference is valid, then the server's failure to process this request could be viewed as exceptional. This could happen for example if the reference is valid, but the a different client deletes it. In this scenario, the first client is not doing anything wrong.
In short: No. Your API should be "user-friendly" meaning, if there is an error it should return it in a way that the user can figure out what the problem was. Returning 404 is like saying that the service was not found which is not true. The response should be 403 - cause it could be that the resource with the ID that the client tries to approach belong to a different client!
In addition, the response should contain an error message/code (in the body) which can be parsed and analyzed by the client.
This is a bit grey area.
Although the 500 response code looks like a good fit because of its broader context, the 404 response code could also be considered.
The reason that I am not sure about the 404 code is the main purpose of your request. The request is sent to create a new resource. It is not for retrieving an existing resource. Though the root cause is the "Not Found" resource, the intention of the request is for a new entity. Getting the 404 response code might cause ambiguity for the client. Therefore, the 500 with a good explanation looks like a better option.
I can clearly state that the 400 response code is not convenient for this case because there is nothing wrong with the request syntax.
The following definitions from MDN Web Docs - HTTP response status codes might help to make a decision.
400 Bad Request:
The server could not understand the request due to invalid syntax.
404 Not Found:
The server can not find the requested resource. In the browser, this
means the URL is not recognized. In an API, this can also mean that
the endpoint is valid but the resource itself does not exist. Servers
may also send this response instead of 403 to hide the existence of a
resource from an unauthorized client. This response code is probably
the most famous one due to its frequent occurrence on the web.
500 Internal Server Error:
The server has encountered a situation it doesn't know how to handle.
4xx is entitled "Client Error" in the standard
5xx is entitled "Server Error"
If the server is 100% sure that the reference to Bar could not be correct (that id is totally invalid format or couldn't have existed) then that's a straight up 400 Bad Request.
If the server allowed someone to delete that Bar where such deletion should not be allowed (Foo should go down with it) then that's a 500 Internal Server Error.
Here the client is creating a Foo with a dangling reference to a Bar (since it's a POST, if it were updating a Foo it would be a PUT). The client got a reference to the referenced Bar somehow and can presumably find an appropriate existing Bar if it tried again. In that case, the server returns 409 Conflict to signal that the request, while valid, is in conflict with the state of the server and needs to be dropped or reconstructed so that it is consistent with the state of the server. The 409 response should specify that the problem is that the referenced Bar does not exist.