I need to write an API to check if a user name already exists in a database.
I want my server (Struts Action class instance in tomcat server) to return true/false.
Its something like this
checkUserName?userName=john
I want to know what is the standard way to do this?
Shall I return a JSON response with just one boolean value ... seems like a overkill.
Shall I do something like manually setting the HTTP header to 200 or 404 (for true/false), but that seems to violate the actual purpose of using the headers which I believe must only be used to indicate network failures etc.
(Too long for a comment.)
I don't see any reason not to return a standard JSON response with something indicating whether or not the user name exists. That's what APIs do: there's nothing "overkill" about providing a response useful across clients.
To your second point: headers do a lot more than "indicate network problems". A 404 isn't a network problem, it means the requested resource doesn't exist. It is not appropriate in your case, because you're not requesting a resource: the resource is checkUserName, which does exist. If instead your request was /userByName/john a 404 would be appropriate if the user didn't exist. That's not an appropriate request in this case, because you don't want to return the user.
A 401 isn't a network problem, it's an authentication issue. A 302 isn't a network problem, it's a redirect. Etc. Using HTTP response codes is entirely appropriate, if they match your requests.
Related
Well I have an microservice that is developed in spring boot and it call to an external database to fetch the results but now sometimes it does not able to fetch the results from external database as the database itself does not have data because there is a selective query fired from microservice to fetch the results from database , so in these conditions which correct http status code I should return , shall I return http status code 204. Please advise.
shall I return http status code 204
My current thought is "probably not". The specification of 204 No Content includes this remark:
The 204 response allows a server to indicate that the action has been successfully applied to the target resource, while implying that the user agent does not need to traverse away from its current "document view" (if any).
In cases where you have a GET request that returns an empty document, I prefer a 200 OK with Content-Length 0.
The choice of 2xx vs 4xx comes down to what information you are including in the response-body: in the case of GET, if you are returning a representation of the resource, then you should be returning a 200. If you are returning a document that describes an error, you should return one of the 4xx codes.
Which of these is the right answer will depend on your resource model. It's perfectly reasonable for a search to return no results; in that case, returning a representation of an empty result set would call for a 200. If the absence of data means (semantics) that the requested resource doesn't exist (or more precisely, doesn't have a current representation) then you should return a 404.
REST doesn't tell you which of these is "right" - it just gives us a common language for describing the alternative we have chosen in a way that general purpose components can understand what is going on.
I have a REST service which is a POST to create a user, if the user does not exist, the user is created, and the service returns a 200 with the user in a json format.
Case 1: What if the user exists already, do I return a functionnal exception, so a json containing an error (all of this managed by the error handling of spring boot), and what about the http status code
Some people say to send a 303 or a 409 ... many different answers, and what about the response body in that case?
Case 2: What if in the backend we have let say a rule on the name (like containing a space) which returns an error (space not allowed in a name), same questions, do i have to return a functionnal exception and what about the http status code in this case
Somehow I want the API consumer to know what kind of json structure to handle and i guess the http status code helps for that ?
It all depends on how one interprets the various http status codes and how user friendly do you want your HTTP payload responses to be. Below are few suggestions:
NEW USER CREATED : If its a new user and gets created successfully in the backend then you return http status code 201. This is a technical status code. You can also return a functional status in the response body mentioning "User created"
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
USER ALREADY EXISTS : If the user already exists, you should respond with http status code 200 with a response payload body mentioning a functional status "User already exists"
USER CREATION FAILED : If the new user rules are not satisfied at the backend service and it throws an error then the http status code of 400 can be used and functional status in response payload of "User creation failed, please conform to the user name rules" https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400
For an API Consumer to know everything about your API's, you may want to provide a API specification document. You may use open API spec(previously known as swagger) https://swagger.io/specification/
Somehow I want the API consumer to know what kind of json structure to handle and i guess the http status code helps for that ?
Not quite.
The HTTP status code is meta data in the transfer documents over a network domain. It communicates the overall semantics of the response (for instance, is the body of the message a representation of a resource, or a representation of an error? is this response cachable? and so on).
For unsafe requests in particular, cache invalidation is sensitive to "non-error status codes". The difference between 303 (non-error status code) and 409 (error status code) can be significant.
The Content-Type header gives you a mechanism to describe the kind (schema) of the message you are returning (ex: application/problem+json).
The way I think about it: the information for your bespoke consumer belongs in the message-body; we lift data from the message-body to the HTTP metadata so that general-purpose components can take advantage of that information (for example, by invalidating cache entries).
So we would normally start by defining the schema and semantics of the message body, and making sure that we have intelligent ways to communicate all of the things we want the caller to know. In other words, we are defining the documents that we pass to the client, and how to extract information from them.
Information that HTTP components need to know get copied from our bespoke document into the standardized forms (status code, headers).
Where things get complicated: the fact that something is an "error" in your domain, that doesn't necessarily mean that it should also be considered to be an "error" in the transfer of documents over a network domain.
A common case: we are using our API to navigate some work through a process; that process has a happy path, and also some exceptional paths that we normally try to avoid (accounts are overdrawn, items are out of stock, etc).
An HTTP request can move work from the happy path to an exception path and still be a "success" in the transfer of documents domain.
The easiest heuristic I know is to think about previously cached copies of responses by the same target URI. If those responses are still re-usable, then you are probably looking at a 4xx status code. If the responses should be invalidated, then you are probably looking at a 2xx or 3xx status code.
Which HTTP status code is correct for Subscription Canceled exception?
I need to throw an exception when the user tries to accesses a certain page.
I checked a few statuses like Payment Required, but it's not satisfying the requirement. Any suggestion?
Which HTTP status code is correct for Subscription cancel exception?
HTTP status codes belong to the transfer documents over a network domain.
So the specifics of what is going on in your domain don't particularly matter - the idea is to understand the error condition in terms of document transfer, and work from there.
In this case, the best fit is likely 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
It may help to imagine how this example would play out on a web site. For the human user, you would return a bunch of HTML explaining that their subscription had been cancelled, perhaps with links to resources that would allow the user to re-subscribe, and so on.
For the browser, you would have the HTTP meta data, including the status code, so that the browser would understand the general purpose semantics of the message (for instance, should earlier representations of the resource be invalidated in the cache).
it's a API request from front-end.
This doesn't really enter into the discussion; the motivation for the uniform interface is that we can swap out the implementations at either end of the conversation and the semantics of the self descriptive messages don't change.
I would say that correct Response code is:
401 Unauthorized
Since by the definition the user Cancelled his subscription and cannot more access paid content, therefore user is Unauthorized for that.
In the other words User is Authenticated but Unaouthorized to do this request.
I'd like to offer an alternative solution. 403 errors make a lot of sense here, as access is denied for a resource. However, this could be difficult to handle in the front-end, because it's indiscernible from a 403 error caused by lacking permissions or roles. A 402 error is non-standard, but "Payment Required" would be easier to program around. If using a non-standard HTTP code is allowed, I believe this to be a more suitable status to return from an API based on a cancelled subscription, or a lack of a valid subscription in general.
im writing a java application that sends a post request to a server and expect a json from the server. Now when i need to get the response from the server do i only need to get it from the inputStream when the http code is 200 (HTTP OK) or is there any other cases ? , example :
//...
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// only here try to get the response
}
//...
It depends on how the server is implemented. Check the API, if the server has one. If it's internal, ask your server guy.
Generally speaking, if your response code is either 2xx or 3xx, I would check the response anyway...
If the server your communicating with is following the spec then either 200 or 201 responses are valid to contain an entity. A 204 response is successful but has no data in the response.
See section 9.5 here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5 for details of acceptable responses to a POST. Extract below:
The action performed by the POST method might not result in a resource
that can be identified by a URI. In this case, either 200 (OK) or 204
(No Content) is the appropriate response status, depending on whether
or not the response includes an entity that describes the result.
If a resource has been created on the origin server, the response
SHOULD be 201 (Created) and contain an entity which describes the
status of the request and refers to the new resource, and a Location
header (see section 14.30).
There are three things to consider:
All 2xx codes denote success of some sort. But depending on the exact code, your reading code might be different. (204 for example means success but no content.)
There are redirecting codes (3xx). These are usually automatically followed by the http client library but you can also set them not to, in which case you need to have custom code that handles these cases.
There can be valuable information returned in the stream even if you get a code that denotes an error. Whether you want to process it depends on your exact needs.
I am using RESTlet and I have created a resource. I handle POST by overriding acceptRepresentation method.
The client should send me some data, then I store it to DB, set response to 201 (SUCCESS_CREATED) and I need to return some data to the client, but return type of acceptRepresentation is void.
In my case, I need to return some identificator so that client can access that resource.
For example, if I had a resource with URL /resource and the client sends POST request I add a new row in DB and its address should be /resource/{id}. I need to send {id}.
Am I doing something wrong? Does REST principles allow to return something after POST? If yes, how can I do it, and if no what is the way to handle this situation?
REST just says that you should conform to the uniform interface. In other words, it says you should do what POST is supposed to do as per the HTTP spec. Here is the quote from that spec that is relevant,
If a resource has been created on the
origin server, the response SHOULD
be 201 (Created) and contain an entity
which describes the status of the
request and refers to the new
resource, and a Location header
(see section 14.30).
As you can see from this, you have two places where you can indicate to the client where the newly created resource resides. The Location header should have an URL that points to the new resource and you can return an entity with the details also.
I'm not sure what the difference between overriding acceptRepresentation() and overriding post() but this example shows how to return a response from a POST.
I'd forgo sending anything in the body of the response. Just set Location: to the (full) URL of the newly created resource.
Your description suggests that this is exactly the semantics you:
POST a thing to create it
Respond with enough to know two things:
That the creation happened (the 201)
Where to find the new thing (the Location header)
Anything else is superfluous.
Two different questions:
Does the REST application pattern support returning data in a POST?
I don't think REST explicitly disallows it, but the preferred treatment is spelled out in Darrel's answer.
Does the RESTlet framework allow returning data in a POST?
Yes, even though it returns void, in a class which extends Resource, you have full access to the Response object object via the getResponse() method. So you can call getResponse().setEntity() with whatever data you want.
Output it in whatever format is requested. That might be:
<success>
<id>5483</id>
</success>
Or:
{ "type": "success", "id": 5483 }
It depends on what you usually do. If they're not expecting the data, they should just ignore it, but any client that wants to handle it properly should be able to.
If you respond 201 Created with an entity body, rather than a Location redirect, then it's a good idea to include a Content-Location header pointing to the resource that is being represented in the response.
This will avoid potential confusion - in which a client could (justifiably) assume that the response entity actually represents a new state of the 'creator', and not the created resource.
> POST /collection
> ..new item..
< 201 Created
< Location: /collection/1354
< Content-Location: /collection/1354
< <div class="item">This is the new item that was created</div>