Which 4xx http status code for REST [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
We have a RESTful architecture and I have a question regarding to exceptions and http statuses for our API.
We use 400 for cases:
value mismatch (for instance, expected 100 but was 99)
violations of #Size, #Min, #Max, #Nullable anc etc
Use 422 (unprocessable entity) for cases when something wrong with logic, but it is not a client mistake. For example, trying to set category to product which already has one. This is unpredictable on the client side.
Finally, we use 409 (conflict) for cases when it is a client's error.
For example, if he is trying to send invalid Date format via JSON. Or registration date is far away before current.
But one case fits into a few categories:
We have a Tax field which is integral number.
If client sends fractional Tax then exception should be thrown.
From one side, this is clearly 400 and client should see 'Tax cannot be fractional'.
But, from other side - it is a client's programmer error, since he is trying to send Double/Float instead of Integer/Long (i.e. he sends another type, it's like pass Long instead of String) and 409 should be thrown.
What should I choose: 400 or 409 for TypeMismatch in Numbers case?
And if 400, why should I make an exusement for Number types but throw 409 for Date/String cases of TypeMismatch?
I would prefer answers with a definite logic rather then a "I think". This is not a discussion.

I concur with the opinion-based question comment, but I'll also throw this out there:

Opinion: Since types are more fundamental I would throw a 409

Honestly I would prefer status code 400 or 422 for your use case since the provided entity can't be processed because of its content. This can be something structural (wrong types, missing required fields, ...) or data validation (wrong format using regexp, not allowed values, duplicate values, ...).
Status code 409 should be rather used for optimistic locking, as described in the link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html:
10.4.10 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 information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For 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. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
Hope it helps you,
Thierry

I don't see why you would a 409 for any of these cases.
Here is what Wikipedia says about 409:
Indicates that the request could not be processed because of conflict
in the request, such as an edit conflict in the case of multiple
updates.
I would use 400 for the number types as well as the Date/String case.
But it is a matter of personal flavor, both status codes are possible as long as you stay consistent throughout your API.

Related

Making an existing API more RESTful [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've an existing API, which I'm attempting to make more RESTful.
The app involves a Gifter and a Giftee. The Gifter buys something for the Giftee, and sends the link to the gift on whatsapp.
Before creating a user account for the Giftee, I first do some verification by tying the person to a phone number. I've 2 endpoints:
/sendSmsCode
/verifyUser
First endpoint sends an sms code to the phone number, and second endpoint takes the sms codes and verifies its correct. /verifyUser then returns a session token. This session token is then used to accept the gift and create the user.
Obviously these are not RESTful endpoints. But the user hasn't been created at this stage so I can't do something like /users/{id}/send-sms (which I know wouldn't be too RESTful either given it includes a verb).
Any suggestions?
I meant to post a comment, but it's overly long for a comment, so I'm posting it as an answer (although it may not answer your question directly).
Obviously these are not RESTful endpoints.
REST is an architectural style and not a cookbook for designing URIs. It's never enough to stress that REST itself doesn't care about the URI spelling, as long as the URIs comply with the RFC 3986.
To be considered RESTful, an application must follows a set of constraints defined in the chapter 5 of Roy Thomas Fielding's dissertation.
You mention use use a session token in your question. If the session state is kept on the server, than it's not RESTful at all. REST applications are meant to be stateless, where one request contains all required information to be understood by the server, without taking advantage of session state stored on the server.
I can't do something like /users/{id}/send-sms (which I know wouldn't be too RESTful either given it includes a verb).
One important concept of the REST architectural style is the resource and their identifiers.
The URI (or Universal Resource Identifier) is meant to identify a resource rather than expressing the operation over the resources. The operation to be performed over the resource can be expressed by the request method. The request method is the primary source of request semantics, indicating the purpose for which the client has made this request and what is expected by the client as a successful result.
To properly identify resources, it's a natural choice using nouns (as the verb is expressed by the HTTP method). But it's not mandatory to use only nouns. As long as you comply with the REST constraints, you surely can design a RESTful API with some verbs here and there (and possibly use POST for sending data to such endpoints).

Appropriate HTTP Method for 'Single Read' REST API

We have a REST API that reads and deletes the record from database and returns the read value back to the client, all in same call. We have exposed it using HTTP POST. Should this be exposed as HTTP GET? What will be the implications in terms of Caching in case we expose it as GET.
First, you should keep in mind that one of the reasons that we care that a request is safe or idempotent is that the network is unreliable. Some non zero number of responses to the query are going to be lost, and what do you want to do about that?
A protocol where the client uses GET to request the resource, and then DELETE to acknowledge receipt, may be a more reliable choice than burning the resource on a single response.
Should this be exposed as HTTP GET?
Perhaps. I would not be overly concerned with the fact that the the second GET returns a different response than the first. Safe/idempotent doesn't promise that the response will be the same every time, it just promises that the second request doesn't change the effects.
DELETE, for example, is idempotent, because deleting something twice is the same as deleting it once, even though you might return 200 to the first request and 404/410 to the second.
HTTP does not attempt to require the results of a GET to be safe. What it does is require that the semantics of the operation be safe, and therefore it is a fault of the implementation, not the interface or the user of that interface, if anything happens as a result that causes loss of property (money, BTW, is considered property for the
sake of this definition).
I think the thing to pay attention to here is "loss of property". What kind of damage does it cause if generic components think that GET means GET? and act accordingly (for example, by pre-fetching the resource, or by crawling the API).
But you definitely need to be thinking about the semantics -- are we reading the document, and the delete of the database record is a side effect? or are we deleting the record, and receiving a last known representation as the response?
POST, of course, is also fine -- POST can mean anything.
What will be the implications in terms of Caching in case we expose it as GET.
RFC 7234 - I don't believe there are any particularly unusual implications. You should be able to get the caching behavior you want by specifying the appropriate headers.
If I'm interpreting your use case correctly, then you may want to include a private directive, for example.
As per the above discussion, it looks like PUT request. You should not use GET as it is idempotent because the same data is not available for the second time call. POST is used to create a new resource. So it will be better to use PUT http method for this kind of requirement. Refer below the link for more details.
https://restfulapi.net/http-methods/

Determining the HTTP method for payload transfer from client to server

I have a use case where some context needs to be transferred from the UI to the backend and backend needs to decide and send the response based on that context.
This can be achieved by sending the context through request body and at the server side, by parsing the request body, the representation can be sent in the response body.
My doubt is which http method is suitable for this?
GET: If we use GET, we can send the request body but it is advised that the body should not have any semantics related to the request.
See this: http-get-with-request-body
So I am left with POST or PUT but these corresponds to updating or creating a resource and using them might be little misleading.
So my question is what is the appropriate HTTP method that could be used in this scenario which is acceptable in the RESTful design standpoint.
Appreciate the response.
I am thinking to use POST or PUT as there are no restrictions on consuming the request body on the server side.
EDIT:
I think POST would serve my purpose.
The rfc HTTP RFC 7231 says that POST can be used for:
Providing a block of data, such as the fields entered into an HTML form, to a data-handling process
So the data handling process for me is the backend server and HTML Form is equivalent to any UI element.
So I can make use POST method to send the data to backend and send the existing resource representation as response body with http-status code being 200
Please bear in mind that GET must be used for data retrieval only, without side effects. That is, GET is both safe and idempotent (see more details here).
If the operation is meant to be idempotent, go for PUT:
4.3.4. PUT
The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response. [...]
Otherwise, go for POST, which is a catch all verb:
4.3.3. POST
The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics. [...]
I would go for POST because in REST, PUT is used to create a new resource like user.
There is a PATCH post method, that is for changing things maybe thats what you are looking for
So my question is what is the appropriate HTTP method that could be used in this scenario which is acceptable in the RESTful design standpoint.
The world wide web is about as RESTful an example as you are going to find, and HTML forms only support GET (which should not have a request body) and POST. So POST must be fine (and it is).
More generally, POST can be used for anything; the other methods should be used when they are a better semantic fit. For example, you can use POST to make a resource unavailable, but DELETE is more explicit, and generic components can do sensible things because they recognize the semantics. PUT is a better choice than POST when what you are intending is to provide the server with a new representation of a resource, and so on.
I am not able to understand why the payload of the HTTP GET is forbidden
Payload of the HTTP GET is forbidden because the standard says "don't do that".
I believe it is written that way to simplify the rules for caching the response. As written, cache implementations only have to worry about header data (including information on the start-line).
But it could be as simple as the fact that the older versions of the standard didn't require that generic components do anything specific with the message-body of a GET request, and therefore modern specifications say "don't do that" in order to maintain backward compatibility. (One of the important constraints in designing long-lived systems is that you don't break older implementations.)

Jersey response containing incorrect data

Apologies: I don't have a simple test case that reproduces this problem, as it happens very intermittently. However, I would greatly appreciate some help regarding how to even begin diagnosing the issue.
I have a Jersey server running on Tomcat.
When the client makes a request, sometimes a response from a totally different request is mixed in with the correct response.
The "correct" request can be of any kind, but the "bad" response which gets mixed in is always from an SSE stream (EventOutput) or an AsyncResponse.
For example, this is the output received by a client through a normal request:
event: message_sent
id: 1
data: {"value":"hello world"}
{"event-id":"13"}event: message_sent
id: 2
data: {"value":"hello world"}
The genuine response {"event-id":"13"} is present... but surrounding that there are two erroneous SSE events.
The method to handle this request returns simply:
return Response.created(uri).entity(eventId).build();
So I don't understand at which point the unwanted data gets sent (unless Response.created() is returning a response object which had already been used for an SSE stream).
The server logs always show the correct output. We know the client is not at fault, however, as we used a packet sniffer to confirm the responses are malformed.
Notes:
For SSE streams, I always check that the EventOutput is not closed before writing to them
When writing to AsyncResponse objects, I always check isSuspended() first (and they are injected with the #Suspended annotation)
Again, any hints or pointers would be such a great help. I've run out of ideas!
After a lot of research, I've concluded that my problem must be (of course) a user error even though I couldn't reproduce the error when I removed the apache proxy from the equation. In my case, I had to be more careful about when considering EventOutputs as closed -- since you can only tell if the connection is open when trying to write to it. In general though, my findings are:
A bug of this kind occurs when you keep references to response objects around, and then write to them after Tomcat has re-used them for another request. This could be a list of e.g. AsyncResponse or EventOutput objects which you need to keep around to resume or write to at a later time.
However, if it's a bug which is difficult to track down and you need a solution, there is a Tomcat setting which will disable the re-use of these objects at the cost of performance, as it says here: https://tomcat.apache.org/tomcat-8.0-doc/security-howto.html
Setting org.apache.catalina.connector.RECYCLE_FACADES system property
to true will cause a new facade object to be created for each request.
This reduces the chances of a bug in an application exposing data from
one request to another.
(Don't be confused by the name; RECYCLE_FACADES=true means that the facades will not get reused, and new ones will get created as they are needed).
There are examples of application bugs like this only manifesting when behind an apache proxy, so if the bug disappears if you access Tomcat directly it doesn't necessarily mean that apache is at fault.
As I say, it's unlikely for this to be caused by a bug in Tomcat, Apache or the mod_proxy_ajp... but if you are an unlucky one, you can try using another connector (mod_jk, for example).

Defensively checking inputs in client. Is this a good practice? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Is it a good practice to defensively check for null/empty inputs in client ? In the server this check is happening of whether or not input is null and an exception is thrown accordingly, should client also make a check in order to avoid a call to the webservice ?
Under the best circumstances, it is a performance improvement, and nothing else.
Under the worst circumstances, the client side checking can drift away from what the server accepts, actually introducing bugs due to inconsistent deployments.
In either case, you don't typically have control over the client environment, so you cannot assume the client-side check was performed. Malicious users can inject their own client-side code which will permit non-valid inputs to be sent to the server, so server-side checking is still strongly required.
I would recommend that you do client-side checks, but I would also recommend that you take the care to ensure that your client-side checks are synchronized with your server-side checks, such that your client doesn't start filtering inputs in a different manner than your server would. If that becomes too problematic, error on making the server side checking correct. It's the only real defense point.
It's good practice to do whatever you need to do to protect your server, whatever that may be.
Always do checking server side, you never know where data is going to come from.
Do checking client side if you have some reason for notifying the user of their mistake before sending data to a server. For example, a client-side validation of an integer input can, e.g., update a warning label as the user is typing without requiring round-trip validation to the server. Client-side checks are essentially a first line of action for displaying clear validation errors to the user, but really they are nothing more than UI performance improvements. If you don't want to do that, then you don't need to do that. If you only want to do that for certain values, you only need to do that for certain values.
Perhaps your server already generates reasonable information about validation errors, in which case you could display those to the client. It really depends on your situation and needs.
For example, lets say the client displays a series of dialogs asking for input before finally sending a request to the server. It's irritating for the user if they aren't notified of an invalid input until after they go through the entire series of dialogs. This is a good case for client-side validation at each step of the input.
Note that the cost of client-side validation is that you need to make sure to maintain it to match the actual server-side rules if they change.
It's also good practice to think a little about your specific requirements and choose an appropriate course of action to make sure those requirements are met, rather than asking vague questions about generic, situation-agnostic "good practice".
Personally, I try my best to have server-side validation report useful information, and I don't do any initial client-side validation. I then add client-side validation later, after higher priority work is complete and after determining that the UX would clearly benefit from it.
Yes, in order to keep the bandwidth and the server load as low as possible, you should always add client-side validation as well. Even a thin-client can do easy validations like null/empty-checks.
If you have some complex validation depending on many different inputs (cross-validation) or maybe complicated checksum calculations, you might skip the client-side validation and do it only on server side.
Server side validation is always needed though, because as you can see, the client cannot be trusted if you would now decide to not validate.

Categories