Best Approach for Http Request Handling from Api - rest

What is the best practise for api return values for basic db operations while we are trying to add,delete,create,update etc..?
1-(If exists what is most suitable status codes for these operations?)Just returning corresponding http status code?(e.g. return 204 for delete operation,201 create operation,500 for "data does not exist" etc.)
2-Return boolean
3-Return custom exception
Shortly,Assume we have project A and it is using api of project B. And B is trying to delete a record from db with a spesific id, but this id does not exist in db.For such scenario, what should we do ?

1-(If exists what is most suitable status codes for these operations?)Just returning corresponding http status code?(e.g. return 204 for delete operation,201 create operation,500 for "data does not exist" etc.)
Returning 204 for deleting and 201 for creation is absolutely fine, but just try to think about what is the most descriptive response code from the perspective of the requester. Also, remember that 500 response codes are used for when something is wrong on the server side (e.g. an unexpected exception).
Shortly,Assume we have project A and it is using api of project B. And B is trying to delete a record from db with a spesific id, but this id does not exist in db.For such scenario, what should we do ?
Again, think about what would be the most helpful error to the requester. 404 Not Found would accurately describe why the operation failed. You can place an error message in the response body if you want to make it more descriptive - but you don't have to.

Related

what is the best Http code to identify idempotent operation conflict

i develop res service at which it take unique id parameter each call, but when the same id used more than once it should retrieve the same response was retrieved the first time and status code specify error, i am looking for the best status code for that , some post use "409 Conflict" and some "406 Not Acceptable", which to use ?
409 is better, because 406 is mostly used to represent header not acceptable.
406 Not Acceptable The requested resource is capable of generating
only content not acceptable according to the Accept headers sent in
the request.
409 (Conflict) means your request is duplicated.
409 Conflict Indicates that the request could not be processed because
of conflict in the request, such as an edit conflict between multiple
simultaneous updates.
I would like to put a different opinion on the table.
"Why should we return 409 always and bother client to handle these scenarios? Why should client be bothered about if item was created as part of current request or one of past tries?"
I feel for a simple scenarios like "POST on collection to create a resource instance" client could be simplified if server returns 201 even in the case of idempotent response.
However, we should also make sure that this simplification does not create confusion in some scenarios like:
Resource was created with initial version V1 by POST request from a client. This resource then get updated and moves to version V2. Now for some reason the initial client retries POST request with the same Idempotency token.
I believe the later one should be returned as 409, since this is a conflict.
POST is expected to create an initial version of the resource with the data present in request. Since this is duplicate request, we would rather fetch existing resource instance and return to client. That resource state may not have all fields as specified in the create request, and hence conflicting.

on POST what if entity exists - what is the correct response

I have a RESTful API where one can GET Nodes and Post Nodes - basic stuff.
My "problem" is this:
When a user posts a new node, and that node already exists.
Should I return
400 bad request
409 conflict
200 and the existing node
Im leaning towards 200 and returning the existing node.
But the 409 and then letting the user get the correct node by themselves seems more "correct" if you will.
What is the "best practice" in this matter, for RESTful api's?
The expected result of a POST is the creation of a new resource along with a 201 CREATED status code. Returning 200 OK is not appropriate because the request was not a success. Also see the RFC:
200 OK
The request has succeeded. The information returned with the response
is dependent on the method used in the request, for example:
GET an entity corresponding to the requested resource is sent in the
response;
HEAD the entity-header fields corresponding to the requested resource
are sent in the response without any message-body;
POST an entity describing or containing the result of the action;
Was there something wrong with the request? No. So 400 BAD REQUEST is not really appropriate either.
409 CONFLICT
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough
Is the user able to resolve the conflict? Yes, probably. If the conflict arises for example because a username is already taken, you can return that as error message to the user so that he can pick another username and thus resolving the conflict.
I would go with the 409.

Rest service returns 404

What is the best practice in return codes if a call to a rest service executes a database query, no results are found and it returns.
Should this be a 404 or a 200 with a message stating no records?
The URL has resolved correctly and no server error has occurred just that there are no records returned.
EDIT:
Example url is:
http://localhost/app/pr_xyz/1234
Used to retrieve a list of xyz that belong to the existing user 1234. The user id 1234 has already been retrieved and is known to exist in the database. This URL (pr_xyz) is just to retrieve a list of xyz that belong to that user.
The relationship is 1 user to 0 or many xyz.
In this case the existing user has no xyz. Should this be a 404 or 200 with meaningful message.
Also I have no control over the URL.
Agree with #Satya, it should be a 200, but we can arrive at the answer by working backwards.
So, we start with the full list of HTTP status codes.. Start from the bottom.
Is it a server error? No? Then it's not a 5xx
Is it a client error? Maybe? Perhaps it's not a 4xx
It's obviously not a redirect, so it's not a 3xx.
Is it a successful call? Perhaps.
Are you returning a provisional response? No, it's not a 1xx either.
So by process of elimination, which are looking at the 2xx codes. Exactly which would be a good fit depends on the semantics of your application.
Since, this is not a DELETE call, then I probably wouldn't use 204 No Content, which is probably the only good alternative. It's not that there's no content.
There is content: "0 results found". Google doesn't show you a blank page when there are no search results.
So we arrive at 200, as well as returning a meaningful body. If you were returning raw results, then you might want to consider wrapping them in a search-results object to provide some meta-data.
Ah! So wait, what if instead of search results, you are indicating a collection of RESTful resources?
GET /items
In this case, I would still return a 200 with a body that says there are no items.
What if, you were trying to retrieve a particular resource?
GET /items/1234
In this case, yes, you want to imply that item 1234 does not exist, and you should return a 404.

What's the best return code for "#unique" violations?

I'm working on a RESTful web API with a Hibernate powered back-end. So far, we've mapped a few error codes. For instance, when #Version validation fails, our API returns HTTP error code 409.
Now, we need to map the best error code to be returned when unique validation fails. For instance, my API has a business rule which says that there cannot be two instances of entity A with the same name. For instance, if I have a record in my DB with name = "XYZ", I cannot create another record in the database with the same name "XYZ". What would be the best return code in this case? 409 as well?
I've done some research in both "REST in Practice" book and Google, and 409 seems to be mostly associated with #Version, I couldn't any references to 409 being used with unique validations.
Any help is greatly appreciated! Thanks!
I would first consider 422 Unprocessable Entity:
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity, and the
syntax of the request entity is correct but was unable to process the contained
instructions.
In this case, the contained instructions are "please create this new resource".
409 Conflict is also often used, the argument being that the existence of the resource is in conflict with the attempt to create a new one:
The 409 (Conflict) status code indicates that the request could not
be completed due to a conflict with the current state of the target
resource. This code is used in situations where the user might be
able to resolve the conflict and resubmit the request.
The rest of the explanation for this response code is about resolving the conflict, which isn't possible in your case. That's why I lean away from this response code.
A third option would be 403 Forbidden:
The 403 (Forbidden) status code indicates that the server
understood the request but refuses to authorize it. [..] However, a
request might be forbidden for reasons unrelated to the
credentials.
Most people get scared off of this code by the auth implications, but the text clearly states that it's appropriate in other situations.
Without much more information about your system, nobody's going to be able to tell you the exact correct code to use. Take a look at the definitions of those responses and pick the one that best meets your needs. Whichever response code you select, make sure the response entity clearly outlines the problem so the client can correct it.

REST API error code when updating a resource that was deleted in a previous operation

Let's say we have a PUT(update) operation on a resource that was already deleted from the server
What should be the API response code ?
4xx - client issue, don't try to send the same query again
or
5xx - server issue, the resource couldn't be found on server
or
neither of these above ?
First of all, be careful with mapping CRUD operations to HTTP methods. PUT is not an update method. PUT is a request to replace the entity stored under the URI with the entity being supplied. This can be used to update, if the full representation is given (no partial updates with PUT, please) but can also be used to create, when you know the full representation and the resource URI.
So, the answer really depends on the server-side semantics. In principle, if the resource was already deleted and a GET to the same URI would return a 404, then a PUT should recreate it, with the representation supplied.
If that's not desired, and you don't want a client to be able to recreate a resource that was deleted before, then I'd say your deleted resource should return a 410 Gone response code when the client tries a GET on the URI, making it clear that the resource existed at some point but it's not coming back, and an attempt to replace it with a new representation should fail with a 409 Conflict, detailing how the current state doesn't allow that.