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

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.

Related

Browser to issue new HTTP request based on response from another HTTP request

I'm looking to dynamically issue a new HTTP request from the client/browser based on response from an earlier HTTP request, in the same page load. Basically, the flow would look something like this:
Issue HTTP request to www.site1.com/fetch, and parse response to get some string mydata.
Issue HTTP request to www.site2.com/lookup?key={mydata}, substituting in the data just obtained. This call should be done in the same page load.
This is related to HTTP redirections, but it's done on the client-side with more flexibility, to possibly a different domain.
I think client-side JS is the best way to achieve this (perhaps with some kind of callback), but I'm open to other ideas.

Is using a query string in POST request a bad practice?

There is a system that sends POST requests from frontend to backend. These POST requests do not use the body to pass the data to the server; instead, it uses query strings in the URL params.
These requests do not send files or JSON, only several string params.
W3C does not describe that situation https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
Is it a bad practice to use query strings for POST requests, and if there any negative consequences of using that from security or performance or architecture reasons?
Are there any conventions that define the usage of body or query strings for different types of requests?
Reminder: In 2014, RFC2616 was replaced by multiple RFCs (7230-7237).
Is using a query string in POST request a bad practice?
Not if you know what you are doing.
Mechanically, it is all fine: are we allowed to use POST with a target-uri that includes a query-part? Yes. Are we allowed to use POST with an empty request body? Yes. Are we allowed to do both of those things at the same time? Yes.
The hard part: will this POST request invalidate the correct representations from the cache?
Cache-invalidation happens when the server returns a non-error response to an unsafe request (POST is an unsafe request method). The representations that are invalidated are those that match the target-uri of the unsafe request.
GET /foo?a=b HTTP/2.0
POST /foo?a=b HTTP/2.0
Here, if the POST is successful, the representations cached after the successful GET request will be invalidated in the cache.
GET /foo HTTP/2.0
POST /foo?a=b HTTP/2.0
Here, the effective request-uri is not the same, which means that general purpose components won't invalidate the cached representations of /foo.
There's nothing wrong with using query parameters in a URL in a POST request, with or without a request body. If it makes semantic sense for your request, it's fine. The POST method in itself has a semantic meaning distinct from GET, it doesn't require a request body to be useful, and the URL is yet distinct from that again. A classic example might be:
POST /foo/bar?token=83q2fn2093c8jm203
I.e., passing some sort of token through the URL.
There's no general security problem here, since anyone who could intercept this POST request to read the URL could also read its body data; you'll hardly find an attacker in a position that allows them to read the URL but not the body. However, URLs are typically logged in server access logs and browser histories, while request bodies aren't; that may or may not be worth considering, depending on what information you're transporting in those parameters and who has access to those logs.

Which HTTP code should return as status?

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.

something wrong with jsonp data, How to get the data

But it returns -403 why
but when I click that, It comes out this
how can I get the message
The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it.. After one-line check with Fetch API the answer is: server is not handling Cross Origin Resource Sharing - making cross-origin AJAX is not possible. You can avoid it by using simple local HTTP server (e.g. in Python) to get data from server (e.g. with requests) and self-serve it (e.g. with Flask).
Check it in JS console:
fetch('https://api.bilibili.com/x/web-show/res/loc?jsonp=jsonp&pf=7&id=1695').then(r=>r.json()).then(json=>console.log(json))

Parsing JSONP Response in Javascript when 4xx or 5xx Http Error Code is Present

I am implementing an application which relies upon communication between a JavaScript client and a server which knows how to respond to the client using JSONP notation.
I am attempting to handle the case in my Javascript client where my server returns with an http status code of 4xx or 5xx. Currently what I'm seeing is that the script is not evaluated as the browser believes it to be an error (which it is.) However, I still want to read what my server has to say in the event of this 4xx or 5xx response code in my JavaScript client.
I'm seeing that this does raise an error on the script tag element, but I'm concerned that this is not cross browser and will not be a robust solution.
Has anyone had any luck on still parsing a jsonp response even though the http status code is 4xx or 5xx?
I'm beginning to believe I should just use this "set a timeout" solution which "detects" a failure by stating the callback function to the jsonp request would complete within a certain time frame, and if it doesn't, there was an error.
EDIT: I'm temporarily always returning 200 status code when my server detects a jsonp client and then tunneling the error message/status in the json object returned. I was hoping to take advantage of the HTTP status codes but I'm thinking that is no-go for a javscript client.
JSONP is a hack to work-around cross-domain issues. When it works, it works well. But when it doesn't you don't have a way to figure out what went wrong.
setTimeout is another hack on top of the original one. If you must use JSONP and still need error detection (not handling), thats what you'd have to do. There isn't a better solution.
If you control the server, try to use alternatives such as Cross-Origin-Resource-Sharing (CORS), or Flash's crossdomain.xml to allow cross domain requests. If you don't control the server, you can proxy the response through your server to get better control.
One approach when using JSONP is to embed status information in the callback. So the callback function signature would look like
callback(result, status, message)
So if your call looks like
http://myurl.com/?callback=fn
generate code for a successful call that looks like
fn({"data":"my great data"}, 200)
and for an exceptional condition
fn(null, 500, "server error"}
You can check the status of the XHR object (if you are not using a JS library).
if(xhr.readyState == 4){
if(xhr.status == 200){
// good
}else if(xhr.status == 502){
// d'oh
}
}
If you are using jQuery, you can pass in a statusCode to handle special cases for $.ajax

Categories

Resources