Http response codes for invalid data and data conflict [duplicate] - http

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
REST response code for invalid data
Have the following REST resource:
POST /user/{primary_key}
The resource is intended to work like an "ADD/UPDATE" operation. This means that it can be used to:
Create a new user
Update information on an existing user
If a client wanted to create a new user, some information is required:
POST user/{pimary_key}
Paylod:
- Username - (must be unique)
- Password
If a client wants to simply update an existing user, the call only needs to include the primary key and the new/changed information. For example:
POST user/{pimary_key}
Paylod:
- favorite hamburger type
This situation creates the potential for several requests from the client that are invalid:
CONFLICT - The client updates an existing user attempting to change the username to a value that is already in use by a different user.
MISSING INFORMATION - The client attempts to create a new user without including necessary information such as the username and password.
What are the correct HTTP response codes to return in these cases?
Thanks so much!

code 201 for created user, quite obvious
400 for incorrect input parameters is the most suitable, google API uses it
seems 409 the best for conflicting situation like yours
I would only recommend to separate creation and editing, and use different methods for them - POST to create, PUT to update. What if the user was going to modify something, but had a typo? It is better to show an error

Here's a good table of "typical" HTTP responses to RESTful operations.
From that table, here's what's recommended for POST operations:
200 (OK) - if an existing resource has been updated
201 (created) - if a new resource is created
202 (accepted) - accepted for processing but not been completed (Async processing)
301 (Moved Permanently) - the resource URI has been updated
303 (See Other) - e.g. load balancing
400 (bad request) - indicates a bad request
404 (not found) - the resource does not exits
406 (not acceptable) - the server does not support the required representation
409 (conflict) - general conflict
412 (Precondition Failed) e.g. conflict by performing conditional update
415 (unsupported media type) - received representation is not supported
500 (internal server error) - generic error response
503 (Service Unavailable) - The server is currently unable to handle the request

Related

What is the most appropriate HTTP response from a backend service when attempting to remove an entry that no longer exists in the Database?

My team is developing a simple backend service that provides the operations ADD, GET and REMOVE a very simple item. All are triggered by an http request and they do not much besides adding, getting and removing the item from a database.
Regarding the specific scenario in which a REMOVE operation is triggered on a item that is not present in the DB (e.g. was removed before), our question is what should be the response of the service? We having been debating options like 200 + some specific message, 410 - resource gone, amongst other 2XX and 4XX possibilities, but we haven't reached a consensus.
I hope this is not Bikeshedding.
Thank you for your help.
What should be the response of the service?
It's important to highlight that status codes are meant to indicate the result of the server's attempt to understand and satisfy the client request. Having said that, 2xx status codes are unsuitable for this situation and should be avoided:
The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted.
The most suitable status code would be in the 4xx range:
The 4xx (Client Error) class of status code indicates that the client seems to have erred. Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
The 404 status code seems to be what you are looking for, as it indicates that the server can't find the requested resource:
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. A 404 status code does not indicate whether this lack of representation is temporary or permanent; [...]
If you are concerned on how the client will understand the 404 reponse, you could provide them with a payload stating that such resource is no longer available.
And just bear in mind that ADD and REMOVE are not standard HTTP methods. Hopefully that was a typo and you are using POST (or PUT) and DELETE to express operations over your resources.

Status code 400 or 200 for error on another micro-service

My application is currently composed of two micro-services :
A. Subscription micro-service
B. Payment micro-service
It also uses another external service:
C. Payment provider
If a user tries to create a subscription with an invalid card number (let's say his card is blocked) the C. service will return me a 200 with a "success" parameter to "false" (I don't handle this service so I can't do anything about that).
Now my question is, what status code should the Payment (B) and Subscription (A) micro-services return ?
I'm not sure if it's a 4** or a 200 (with a success parameter) because the request itself is ok, the input format is ok (even if the data inside it is invalid).
In this situation, a 200 clearly isn't correct, because the request wasn't successful.
My recommendation in such cases is HTTP 422 Unprocessable Entity, which is defined in WebDAV but widely understood, and indicates that the request was syntactically valid but had semantic errors that prevented successful processing.
If the request is syntactically correct - e.g. card number matches some given regex, but is invalid in an another way it definitely should not be 400 Bad Request. This is simply not a bad request.
It also should no return any of 2XX codes since this codes are dedicated for successful responses and - as you set in body success = false is not a request that was processed successfully.
The code that will be the most appropriate will be 409 Conflict along with clear message describing the problem. It indicates that request failed, clarifies why and states explicitly that after correcting the request it can be resubmitted.

HTTP status code for "no data available" from an external datasource

Scenario:
A POST request is sent to process an order that will result in data retrieval from an external datasource.
There are three possible results:
The datasource returned data for the request
No data was available for the request (this is viewed as an error)
The datasource couldn't be accessed (may be down for maintenance)
An obvious response for 1 is 200: OK or 201: Created (an entity is created from this request).
What status codes would be appropriate for 2 and 3?
Status codes I have considered:
503: Service Unavailable when datasource is down
500: Internal Server Error when datasource is down
502: Bad Gateway when "no data available"
404: Not Found when "no data available"
403: Forbidden when "no data available"
412: Precondition Failed when "no data available"
2) Looking back at this, I agree it should probably be either a 204 No Content or maybe a 200 with a body indicating no records or resources could be found depending on the structure returned.
404's are generally used when the resource URI doesn't exist or a resource in the URI is not found in the case of a restful service.
3) 503 Service Unavailable
The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.
Note: The existence of the 503 status code does not imply that a
server must use it when becoming overloaded. Some servers may wish
to simply refuse the connection.
3) I agree with 503 for this
2) Frankly I think a good argument could be made for using 204 in case 2 You can include metainfo in the header to indicate specifically what 'went wrong'. It really depends on how much you consider this case to be 'an error' at the API level.
If the API itself is functioning as intended, and the request was to a valid endpoint, by an authenticated and authorized user and did not cause the server to malfunction, then very few of the 400 or 500 series errors would really seem to apply.
for example, 404 usually means the URI you called does not exist, if it does exist, then using that code is misleading at least IMHO
**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. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
HTTP 404 - With your own error message like "No data found".
Twitter uses 404.
Reference: https://developer.twitter.com/en/docs/basics/response-codes.html
The datasource returned data for the request
200: OK/201: CREATED
Because everything is working as expected
No data was available for the request (this is viewed as an error)
400: BAD REQUEST
The request was invalid or cannot be otherwise served. An accompanying error message will explain further inside the body.like:
HTTP 400
{
response: null,
code: "USER_101", //should be used customized error codes here
error: "User details not found"
}
The datasource couldn't be accessed (may be down for maintenance)
404: Resource/URI NOT FOUND
The URI requested or resource is invalid
Like: https://www.lipsum.com/list-page
**/list-page** is not defined/found
Find here most frequently used status codes:
200 – OK
Everything is working, The resource has been fetched and is transmitted in the message body.
201 – CREATED
A new resource has been created
204 – NO CONTENT
The resource was successfully deleted, no response body
304 – NOT MODIFIED
This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
400 – BAD REQUEST
The request was invalid or cannot be served. The exact error should be explained in the error payload.
401 – UNAUTHORIZED
The request requires user authentication.
403 – FORBIDDEN
The server understood the request but is refusing it or the access is not allowed.
404 – NOT FOUND
There is no resource behind the URI.
500 – INTERNAL SERVER ERROR API
If an error occurs in the global catch blog, the stack trace should be logged and not returned as a response.
In my opinion the best way to handle this is with a 200 no result object.
Why?
You have a response that you can do something with without a lot of trouble. I searched, everything worked correctly but there wasn't anything in the database to give a result. Therefore, result = null and a message explaining as much. If something found this in the network calls it is not a security risk.
If you are concerned with a security risk then a 204 is probably the best approach.
res.status(200).send({
result: null,
message: 'No result'
});

Which HTTP response code for "This email is already registered"?

I'm creating a RESTful API for creating users that enforces unique email addresses:
Successful POST /users: HTTP 201 Created
If I POST the same email address again, what should the response code be? Is 409 Conflict the appropriate response code?
Yes, 409 is the most appropriate response code here. Even though you are most likely returning 201 on success, you're still POSTing to a resource which is described as a collection, and POSTing a duplicate email is definitely a conflict with "the current state of the resource" as a collection. You should return a response body with a description of the problem, and hyperlinks to help resolve the problem, if possible.
I am not really satisfied with returning a 409 Conflict for an existing registered email - in my opinion, it's not a client error. So let's take a look at how some big tech companies are handling that case (at least how they are doing it in their WEB Site APIs).
Gmail (Google) returns a 200 OK and a JSON object containing a code which is indicating that the email is already registered.
Facebook is also returning a 200 OK but re-renders the content to a recovery page to give the user the option to recover his/her existing account.
Twitter is validating the existing email by an AJAX call
To another resource. The response of the email validation resource is always a 200 OK. The response contains a JSON object containing a flag to indicate if the email is already registered or not.
Amazon is doing it the same way as Facebook. Returning a 200 OK and re-rendering the content to a notification page to inform the user that the account already exists and provide him/her possibilities to take further actions like login or password change.
So all these APIs returning always a 200 OK and presenting to the client/user either additional content to recover their account or an error message which is raised by the body content of the response.
While the accepted answer is correct in showing the correct status code for the task, I want to add that you are introducing a security vulnerability.
If you return a 409 for account registration, you are just exposing a service for account enumeration.
Depends on the application, if the api is public or not, etc, you may want to return a 201 even if the account wasn't created.
+1 to Barts answer - for security reasons. Usually I would agree that 409 is a good status code for sth. that already exists. But in an environment of user accounts/authentication/authorization etc., I would tend to not exposing the existing user accounts in your database.
Of course there are other mechanisms of handling security at this place. If you do not mind to expose a little number of your accounts, you could add a behavior to your application that returns 401 or 403 on numerous 409-events from one IP.
Another option (in general) is to define a status code on your own to have a 2xx that differs from the existing standard 2xx variants. This could be an option if you do not want to handle an "already exists" as an error. However, this would be regarded as non-standard and would have the same unsafe character like a 409 in your concrete example.
I often use the (WebDAV extension) HTTP 422 Unprocessable Entity:
The request was well-formed but was unable to be followed due to semantic errors
409 => Conflict
That mean.
The request could not be completed due to a conflict.
For example, POST ContentStore Folder API cannot complete if the given file or folder name already exists in the parent location.
For registration it is required to have a code that is different from success 200 code, but not an error 4xx code.
As suggested in HTTP response code for POST when resource already exists look at 3XX:
302 Found
303 See Other
In particular
According to RFC 7231, a 303 See Other MAY be used If the result
of processing a POST would be equivalent to a representation of an
existing resource.
The concern about exposure of existing addresses to enumerating bots can be addressed by different means such as captcha.

REST - what error to throw when a partly-invalid request is sent

I'm developing a REST api. To simplify my question, I have an API that allows people to create a new blogpost.
Blogposts can live in categories, and categories are specified by a category id. If a user would supply a category-id that doesn't exist, which HTTP error code is the most appropriate?
404 for Not Found seems bad, so I went with 400 Bad Request for now. Is there a better one?
I assume you are responding to a PUT or POST request on your blog post resource.
I would go with the 400 since the resource you are accessing with the URI is found. The blog post could have been modified if the request content had been correct.
Since this is the content of the sent query that is wrong and not the actual URI of the resource, I would stick with the 400 error.
If however, you are adding the blog post to the category by either PUTting or POSTing to the category, then you can return a 404 Not found.
I agree with Vincent in that, of the available defined status codes, 400 is the best. The client should know whether or not a category id is valid at the time it submits the request, and is therefore providing bad request content to the server.
With regard to some of the other answers provided:
404 Not Found - This is not the correct status to use, since the resource you're sending the request to actually was found - it was just a referenced resource within the provided resource that was not found.
406 Not Acceptable - This status is, like Evert commented, used with the Accept headers; see section 10.4.7 of RFC2616:
The resource identified by the request is only capable of generating
response entities which have content characteristics not acceptable
according to the accept headers sent in the request.
409 Conflict - This status is intended for conflicting states of resources, typically due to modifications to the resource perhaps by another channel or thread. The RFC (section 10.4.10) gives an example:
...if versioning were being used and the entity being PUT
included changes to a resource which conflict with those made by an
earlier (third-party) request, the server might use the 409 response
to indicate that it can't complete the request
HTTP does provide an alternative to 400 - if fitting, you can create your own 4XX status for this situation. In section 6.1.1 of the RFC:
HTTP status codes are extensible. HTTP applications are not required to understand the meaning of all registered status codes, though such understanding is obviously desirable.
You could therefore define your own custom "430 - Referenced Resource Not Found" or something similar. HTTP-abiding clients should, if this status is unknown to them, treat it as a 400, but if clients are being coded specifically to the API, they should be able to handle it as a 430 and work with it appropriately.
What about 409 Conflict which is an application specific violation of a rule? In this this case the category ID of the Blog post must already exist. When you return the 409 conflict reply identify what the user can do to correct the situation so they can retry the POST/PUT.
I think 404 Not Found is the most appropriate response - consider the client has tried to access a category which doesn't exist, so the perfect answer is "I can't find that category!"
404 has a very specific and commonly-used meaning, which is that the URL could not be found. Furthermore, some browsers will use their own 404 error page, confusing things more.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
I would recommend "406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request."
400 isn't bad, though.

Resources