Which HTTP code should return as status? - javascript

I need to create REST API endpoint, and I am not sure which HTTP code to return as status.
Requirements are next:
- My API should accept URL as a parameter
- Make an API call to third-party service (use URL), and get a response
- Return response (content that fetched from third-party service)
In some cases, everything works fine. A call is made to external service, it returns content and status code 200.
But, sometimes there is no content and it returns 404. (Important, it is possible that content will be available in the future.)
From the perspective of my system, it is the regular situation.
Which HTTP code should I return?
202 - Accepted,
204 - No content,
206 - Partial content
or something else?

404 Not Found
The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
In REST-API request and response should only work with current "call". If the content is currently not available it should return 404 status. And It(404) is the exact status that should be returned.
However, if you want to bend the rules, 204 status code seems more appropriate. I'm not recommending you to do this.
204 No Content
The server successfully processed the request and is not returning any content Link.

Instead of creating the actual resources, create a temporary one. Instead of returning a 201 (Created) HTTP response, you can issue a 202 (Accepted) response code. This informs the client that the request has been accepted and understood by the server, but the resource is not (yet) created.
From: http://restcookbook.com/Resources/asynchroneous-operations/

You should return whatever the HTTP status code return by third party service unless your system is wrapping it up and processing it and changing the status.

Related

RESTful alternative to 3xx responses for JavaScript based clients

Several our REST service needs to indicate that further action needs to be taken by the client to fulfill the request (very often that the response to the request can be found under another URI).
In general this is achieved by means of HTTP 3xx responses. However, in case of JavaScript based client the redirection is performed by the browser itself before the response can reach JavaScript code.
Basically what I need is a RESTful way to inform the client (JavaScript code) that the response can be found under another URI and let the client process such a response on its own.
I am thinking about two solutions:
HTTP 200 OK with the entity containing URI to follow. I do not like creating a whole entity carrying only URI. I would rather to achieve this via HTTP headers
HTTP 204 No Content response with the Location header containing the given URI. But here I am not sure if it is "REST compliant". Is it OK to combine HTTP 204 No Content with Location header that is used mainly in redirection (along with HTTP 3xx responses), or when a new resource has been created?
Or is there a better solution?
If I understand you correctly, you have a process, say of 5 steps. After step 5 there is some result prepared, to which you want to point your client, not via HTTP-3xx, but in a cleaner way.
I would suggest, that you make use of the link property in your JSON-response:
{
...
"links": [
...
"result": { "href": "/calculation/1234" }
...
]
}
Your client could take this answer and transform it to a simple link/button.
This is conforming with HATEOAS (Hypermedia As The Engine Of Application State), indicating, that the current state offers the result under a different location which is referenced.
Assuming you have a json response format, you could accept a request parameter like noredirect that when present sets the http response code to 200 and set the real response code in the returned object.
GET /some/resource
200 OK
{
status: 200,
…
}
GET /some/unknown/resource
404 Not Found
{
status: 404,
…
}
GET /some/unknown/resource?noredirect
200 OK
{
status: 404,
…
}

Browser mangling 302 responses from Ajax requests

I have the following.
AJAX request made to server from mydomain.blah.com
Server returns 302 but to a slight different domain blah.com not mydomain.blah.com
Browser appears to mangle response. Instead of the 302 coming into my error callback a response with no response body and no status code is returned.
Further details
Looking at request in IE 10 it is marked as aborted.
In FF , firebug shows the 302 coming back but it never been handled.
To complicate matters (although I don't this is relevant) there are multiple ajax requests sent over.
The reason why the 302 is returned is because my server session is timed out and I am being redirected to a login page. I don't have much control over the server.
I want to get the response code 302 sent from my server into my error callback. This is what I want to achieve.
The ajax calls are being made using JQuery.
Any help appreciated.
If it is offical policy for browsers to "mangle" 302 responses to difference domains from ajax calls then if anyone could provide a reference that would be cool. Then I'd know there is not much I can do about this.

How to tell if an XMLHTTPRequest hit the browser cache

If it possible to tell (within javascript execution) if a GET XMLHTTPRequest hit the browser cache instead of getting its response from the server?
From the XMLHttpRequest spec:
For 304 Not Modified responses that are a result of a user agent
generated conditional request the user agent must act as if the server
gave a 200 OK response with the appropriate content.
In other words, the browser will always give status code 200 OK, even for requests that hit the browser cache.
However, the spec also says:
The user agent must allow author request headers to override automatic cache
validation (e.g. If-None-Match or If-Modified-Since), in which case
304 Not Modified responses must be passed through.
So, there is a workaround to make the 304 Not Modified responses visible to your JavaScript code.
When making an ajax request, You get the response code
if (request.readyState == 4) {
if (request.status == 200) { // this number.
...
status 200 means you are getting a fresh copy of the data:
The request has succeeded. The information returned with the response is dependent on the method used in the request -
status 304 means the data has not changed and you will get it from the browser cache:
If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code.
Read more on Status Code
Update:
You can add a cache buster to your URL to guarantee that you always hit the server:
var ajaxUrl = "/path?cache="+(Math.random()*1000000);
From http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/
For 304 Not Modified responses that are a result of a user agent
generated conditional request the user agent must act as if the server
gave a 200 OK response with the appropriate content. The user agent
must allow author request headers to override automatic cache
validation (e.g. If-None-Match or If-Modified-Since), in which case
304 Not Modified responses must be passed through. [HTTP]
I find this rather vague. My assumption would be if a resource is conditionally requested, you would see the 304 response code. But, as I explained in another comment (source: https://developers.google.com/speed/docs/best-practices/caching), there might not even be a request if the last response server http header for that resource had set Cache-Control: max-age or Expires set sometime in the future. In this case, I'm not sure what ought to happen.
This answer is based on the assumption that you mean browser only cache, with no 304's taking place (modified-since, etag etc).
Check how long the request took - if it was resolved from cache then it should take close to 0ms.
Do you use Firefox's Firebug?
Firebug has a "Net" panel with an "XHR" filtered view. You should be able to inspect the cache info via the request phase bar, checking the status and/or clicking the triangle to inspect "Headers".
Cached or not cached
Not all network requests are equal - some of them are loaded from the
browser cache instead of the network. Firebug provides status codes
for every request so you can quickly scan and see how effectively your
site is using the cache to optimize page load times.
Firebug Net Panel docs are here.
Chrome/Safari/Opera all have similar debugging tools. Just found a good list here (most should have tools to inspect XHR).
EDIT:
In order to somewhat redeem myself...
As ibu has answered, I'd also start by checking the status code of the response.
If you're using jQuery:
statusCode(added 1.5)
Map Default: {}
A map of numeric HTTP codes and functions to be called when the
response has the corresponding code. For example, the following will
alert when the response status is a 404:
$.ajax({
statusCode: {
404: function() {
alert("page not found");
}
}
});
If the request is successful, the status code functions take the same
parameters as the success callback; if it results in an error, they
take the same parameters as the error callback.
jQuery sure does make life easy. :)
To check from a browser such as Google Chrome, hit F12 to open DevTools, navigate to Network, refresh to grab some data, filter by XHR, then click on the correct XHR request. Click on the "headers" sub-tab, then look at Response Headers -> cache-control.
If it says things like no-cache and max-age=0, then you are not caching.
If it says private, then your browser is caching, but the server is not.
If it says public, then you are caching both server side and client side.
More info at Mozilla.org

Using HTTP status codes to reflect success/failure of Web service request?

I'm implementing a Web service that returns a JSON-encoded payload. If the service call fails -- say, due to invalid parameters -- a JSON-encoded error is returned. I'm unsure, however, what HTTP status code should be returned in that situation.
On one hand, it seems like HTTP status codes are for HTTP: even though an application error is being returned, the HTTP transfer itself was successful, suggesting a 200 OK response.
On the other hand, a RESTful approach would seem to suggest that if the caller is attempting to post to a resource, and the JSON parameters of the request are invalid somehow, that a 400 Bad Request is appropriate.
I'm using Prototype on the client side, which has a nice mechanism for automatically dispatching to different callbacks based on HTTP status code (onSuccess and onFailure), so I'm tempted to use status codes to indicate service success or failure, but I'd be interested to hear if anyone has opinions or experience with common practice in this matter.
Thanks!
http status code are just for indicating the status of the application response.
and as you said, if json parameters as somehow invalid, a 400 status code is an appropriate answer.
so yes, it is a really good idea to use http status code. de plus, status code are then easy to understand as they don't change from an application (web services) to another
You should definitely use the proper status codes since they are exactly for this purpose, not to indicate the status of the HTTP request itself. By this way you can redirect the response to the appropriate function/branch before parsing it which will lead to a much tidier code in the client side.

Catching 302 FOUND in JavaScript

I use jQuery to make an AJAX POST request to my server, which can return HTTP response with status 302. Then JavaScript just sends GET request to this URL, while I'd like to redirect user to URL in this response. Is this possible?
The accepted answer does not work for the reasons given. I posted a comment with a link to a question that described a hack to get round the problem of the 302 being transparently handled by the browser:
How to manage a redirect request after a jQuery Ajax call
However, it is a bit of a dirty hack and after much digging around I found what I think is a better solution - use JSON. In this case, you can make all responses to ajax requests have the code 200 and, in the body of the response, you add some sort of JSON object which your ajax response handler can then use in the appropriate manner.
I don't think so. The W3C says that HTTP redirects with certain status codes, including 302, must be transparently followed. Quoted below:
If the response is an HTTP redirect (status code 301, 302, 303 or
307), then it MUST be transparently followed (unless it violates
security or infinite loop precautions). Any other error (including a
401) MUST cause the object to use that error page as the response.
As an experiment, I tried doing Ajax requests from various browsers (Firefox 3.5, Chrome, IE8, IE7, IE6) to a server giving a 302 status code, and showing the status in the browser's request object. In every case, it showed up as 200.
In my problem reason was:
i was using localhost/Home/Test addres for testing the page. But ajax request code using 127.0.0.1/Home/AjaxRequest for url parameter. When the urls are different this error occurs.
maybe it helps someone :)
Rather than asking the Javascript code to Handle 302, it would be better to return a 500 with custom error code+ message on event of 302
function doAjaxCall() {
$.ajaxSetup({complete: onRequestCompleted});
$.get(yourUrl,yourData,yourCallback);
}
function onRequestCompleted(xhr,textStatus) {
if (xhr.status == 302) {
location.href = xhr.getResponseHeader("Location");
}
}

Categories

Resources