REST delete in reality update - rest

i'm currently trying to build simple REST api with one endpoint or users looking like this:
GET /users - get all
GET /users/{id} - get one
POST /users - create
PUT /users/{id} - update
DELETE /users/{id} - delete
The problem is with DELETE, because DELETE in reality only UPDATE user resource with status REMOVED. Is it ok? And which status should I return? I'm currently returning 202 Accepted, as i believe that saying "Resource is accepted to be removed" is ok, but maybe there should be just 200 OK

When designing an API, you should always consider what the giving action means for the user of the API.
The user would not really want to know what happens behind the scenes, but only want a clean and understandable set of actions.
So for you delete action, you should consider, "will this delete the item, from the users perspective?"
Responding with status code 200 most often fine, but remember to send some content with it to support it.
Using many different status code for success does not really give value, so be careful.

RestApiTutorial says this.
DELETE is pretty easy to understand. It is used to delete a
resource identified by a URI.
On successful deletion, return HTTP status 200 (OK) along with a
response body, perhaps the representation of the deleted item (often
demands too much bandwidth), or a wrapped response (see Return Values
below). Either that or return HTTP status 204 (NO CONTENT) with no
response body. In other words, a 204 status with no body, or the
JSEND-style response and HTTP status 200 are the recommended
responses.
But you can use It for your prupose, if It do your Api logic easier to understand to the user.
I Hope It helps you.

The question that you have to ask yourself is:
Does the resource after the DELETE will still be available to the client?
If the answer is yes then I would suggest to use a PATCH you can even use the RFC6902 for that.
If the answer is no then DELETE is fine.
But since you have mention that the idea is to flag the user with a status delete I guess you have the intention to query all deleted user at some point or do something useful with it. Witch seems to be a client [admin] use case so PATCH sounds appropriate.
Regarding the status for DELETE. Some people may prefer to use the 204 No content since you are expecting the resource to be removed.

Related

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

RESTful API: Delete Entity - What should I return as result?

I am implementing a RESTful API and an endpoint of one controller is Delete. Delete does two actions depending of the entity to be removed: it updates the entity or it deletes the entity from the database. If delete updates the entity I would send the HttpStatus 200 and the updated entity. But if the delete removes the entity from the database I would send only the HttpStatus 200. In one case I am returning an object. But in the other case, the object doesn't existe any more. Is it a good approach or I am missing anything?
Short answer
The suitable status codes for a DELETE request that has succeeded are 200, 202 and 204.
Long answer
DELETE does two actions depending of the entity to be removed: it updates the entity or it deletes the entity from the database. [...] Is it a good approach or I am missing anything?
The DELETE method is not meant for performing updates.
See the following quote from the RFC 7231, one of the documents the define the HTTP/1.1 protocol, for details on what the DELETE method is about:
4.3.5. DELETE
The DELETE method requests that the origin server remove the
association between the target resource and its current
functionality. In effect, this method is similar to the rm command
in UNIX: it expresses a deletion operation on the URI mapping of the
origin server rather than an expectation that the previously
associated information be deleted. [...]
If the delete operation has succeded, the server can return one of the following status codes:
202: Indicates that the request has been accepted for processing, but the processing has not been completed.
204: Indicates that the server has
successfully fulfilled the request and that there is no additional
content to send in the response payload body.
200: Indicates that the request has succeeded and the request payload includes a representation of the status of the action.
See the following quote from the same document:
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.
The commonly considered HTTP Statuses for DELETE include:
200 OK (MDN)
202 Accepted (MDN)
204 No Content (MDN)
204 is ideal if your service is not returning any additional info. It is also popular for PUT update requests. Many services return 204 including Docker as shown below:
Ref: https://docs.docker.com/engine/api/v1.24/
However, if you are implementing HATEOAS, it is better to use 200 OK and provide some links for the service. Think of an application that has just issued a delete and needs to navigate a user to a location. Without providing a URL for that location, the client app needs to keep state. Providing a 200 OK with a link allows the REST API to keep state for the client.
The following article describes this issue well (read the blog for more discussion):
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.
If a client encounters a 204 response, it can either give up, go to the entry point of the API, or go back to the previous resource it visited. Neither option is particularly good.
Ref: http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/

Would a 404 be acceptable for a DELETE method being called on a non-existent URL?

I am pretty new to the RESTful world, and at the moment I'm debating whether when calling a delete method on a URL that doesn't exist, whether a 404 Resource Not Found should be returned. At the moment, the code returns a 200 OK code, but this doesn't inform a user that what they wanted to do wasn't possible.
I have looked online and on here, and a lot of people have divided opinions on the matter, with HTTP having no standards on return codes.
(I'm thinking in a scenario where someone wants to delete something but through something like a typo, deletes an invalid resource but through there being no error code returned, isn't informed that the delete was unsuccessful, and doesn't realise the mistake.)
I would return the 404 and allow the front-end developer to decide how to handle the situation. As a front-end developer if my user attempted to delete a resource that did not exist, I would like to handle that situation. It could be that the resource was deleted by another user between the time that I found the resource and the present. On the other hand it could be that there was a typo like you said.
But regardless, I would like to know if the user is attempting to delete a resource that no longer exists so that I may handle the situation appropriately.
But this situation depends on the type of application you are constructing. For example, you may want to return a 410 in the case that another user deleted the resource in the last 5 minutes, then return a 404 for all non-existent URLs. But once again, I would only expect a 200 to be returned if something was actually deleted.
SharePoint REST follows this pattern.

Use of HTTP 204 vs 200 vs 404 to safely signal that a resource doesn't exist

In my REST API I have the normal CRUD endpoints for some resources.
If I do a GET /items/42 and there is no such item, the normal behaviour would be to return a 404 NOT FOUND.
However, one scenario concerns me. In this scenario, a client needs to check if a resource (which is implicitly idenfitied by a token) exists, and if not, create it. So, the client would try to retrieve the resource, and if a 404 is received the client application would display the UI necessary for creating the item, and then proceed to POSTing the new resource. In a way, this is a special kind of resource, because since its ID is derived from other parameters, it's known even before creation. As an example, consider a user sign-up procedure; the client would ask "Do I exist? If no -> register me".
My concern is really whether I ever need to worry about "spurious" 404:s? Considering a server is usually surrounded by API gateways, reverse proxies and such, is there any risk that a 404 NOT FOUND could be produced by a surrounding entity due to some temporary error not related to the REST server itself? If so, it could trick the client into believing that the item is not created yet, and that it should now be created. Even if the resulting POST request to create the item would fail because the item already exists, this isn't very nice because the user may have entered data etc for no reason.
Is this a problem to take into account or just overly paranoid? I guess if clients can't trust a 404 to be idempotent (until the resource is created, of course), many other issues arise. Is there any actual situation where an API gateway or similar would report a 404 on its own?
If this is a valid scenario, do I need a "safer", more explicit response saying that the request definetely succeeded but the resource wasn't found, such as responding with a 200 OK with an empty JSON body or a {isRegistered: false}, a 204 NO CONTENT, or similar? This opens up for other strange things - if a request for a resource that doesn't exist would respond with a 200 accompanied by an empty body, perhaps creation of the item would be a PUT rather than a POST, etc? This seems like a can of worms... It all boils down to "Does a 404 guarantee that the given resource doesn't exist?".
404 is pretty unambiguous : the resource wasn't found and it's a client error (4xx). Normally, server-side errors (5xx) can't interfere and create spurious 404's here.
As an alternative, if the resource to be created is linked to another resource in a unique way, you could use OPTIONS to ask the server if it already exists.
For instance :
OPTIONS /visitors/7883930/user-account
=> Allow: POST,OPTIONS (doesn't exist)
=> Allow: GET,OPTIONS (exists)
The key here is to have a URI that allows accessing the resource without knowing its ID. It is not always possible though.

REST and validation of one field

I'm no expert in this so please tell me if I'm way off :)
I'm trying to define a REST service that handles accounts.
/Accounts/32 (GET to fetch one)
/Accounts (GET to fetch all)
And so on...
However, in the sign up process, before an account is created, I would like to verify a couple of fields, like E-mail and ssn, async before the account is created.
How should I go about doing so? I just want to know if they exist in a combination but I shouldn't get a resource back since it's none of my business. :)
Is it valid to do something like this?
/Accounts?ssn=123&email=a#email.com&operation=verifyexistance
Thanks
// Johan
Interesting question, for me I would prefer to do the following:
HEAD /accounts?ssn=123&email=a#email.com
if response status code is 200 then the resource exist on the server
if response status code is 404 then the resource not available and you can continue with registration
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
I like Anas Salman's answer, which suggests the use of HEAD. That's the ideal method.
But I also think that GET is perfectly fine. You are requesting to get information about the resource (the /accounts collection).
GET /accounts?ssn=123&email=a#example.org
When /accounts sees a request in this format (a GET request with an SSN and email address provided), it has enough information to know to respond appropriately with an affirmative or negative.
The addition of an "operation" verb in the query string is the only unRESTFUL part of your example.