ASIHttpRequest: requestDidFinishSelector vs. requestDidFailSelector - iphone

Before I dive into ASIHttpRequest's source code:
From the documentation (http://allseeing-i.com/ASIHTTPRequest/How-to-use) of ASIHttpRequest it is not completely clear to me when an ASIHttpRequest will call requestDidFinishSelector or requestDidFailSelector.
When does a request fail?
Is it correct to assume that whenever the server responds (with a corresponding HTTP status code, be it a 1xx, 2xx, 3xx, 4xx or 5xx, the request is considered successful, and therefore requestDidFinishSelector will apply?
Is 'failure' the fact that the server could not be reached?
As I type this, this seems to be the most logical answer... anyway.

Yes, ASIHTTPRequest doesn't use HTTP status codes (except for redirection), so it's up to you to look out for problems (ex: 404) in your requestDidFinishSelector selector.
int statusCode = [request responseStatusCode];
NSString *statusMessage = [request responseStatusMessage];
requestDidFailSelector will be called only if there is the server can not be reached (time out, no connection, connection interrupted, ...)

You're right — a request succeeds if the server responds with a HTTP status code. You can ask for this status code by using ASIHTTPRequest's responseStatusCode.
If the request URL is invalid or your app has no access to the Internet, then your request fails. So you should implement requestDidFailSelector (or specify your own error handling method) and handle errors in there in any case.

Related

Which HTTP code should be return from REST API?

im currently working on a website which has Spring at backend and Angularjs at front side and we had discussed about back end responses to handle frontend's message dialogs and i have a question to ask:
Lets say i have an API :
GET : /getstatistics
Request params : fromTime,toTime ( in timestamp format)
And if client make a request with invalid params like a string, which response code should be returned from server ? HTTP 400 bad request and response body with a message " fromTime and toTime should be in timestamp format" or HTTP 200 with same message?
I saw some Google's APIs for example Oauth, they're returning code 200 for a request with invalid access_token but ,in our project my opinion it should be HTTP 400 because Javascript has success and error callbacks, is it better for it just pop a red color dialog with message inside rather than a HTTP 200 code then still need to check the content of the message?
Any advides and opinions are appreciated.
Thanks!
You should be returning a 400 error for bad request. Check out this reference.
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
Please have a look at RFC7231#section-6
A client MUST understand the class of any status code, as indicated by
the first digit
and,
4xx (Client Error): The request contains bad syntax or cannot be
fulfilled
Bad syntax can be something like you've mentioned in your question (making a request with invalid parameters, like a string).
I keep these two references handy whenever I'm designing RESTful APIs, might be helpful for you too:
https://httpstatuses.com/
http://www.restapitutorial.com/httpstatuscodes.html
Yes you are right, the http code should be 400 in your case. Your discussion here normally should be whether you need to return 400 or 422. For this you can check the accepted response for this SO question 400 vs 422 response to POST of data
I think it has something to do with how the parameters are used. If you use the resource, then a 404 should return. If the data is simply not valid then we decide to set a 409 Status to the request. It can't full fill it at 100% because of missing/invalid parameter.
HTTP Status Code "409 Conflict" was for us a good try because it's
definition require to include enough information for the user to
recognize the source of the conflict.
Reference: w3.org/Protocols/
Edit:
In any case, the status code 200 is incorrect here because there is an error. In response, you can then return specific information like this:
{
"errors": [
{
"userMessage": "Sorry, the parameter xxx is not valid",
"internalMessage": "Invalid Time",
"code": 34,
"more info": "http://localhost/"
}
]
}

Post condition check http status

Using a following API:
feed?url=XXX
Validations performed on the parameter url:
If missing: 400 Bad Request
If empty/invalid URL: 422 Unprocessable Entity
If URL don't point to a valid RSS/Atom feed: 422??
What status error should be returned for the 3.?
Unlike validation 2., it is not possible to check the 3. without fetching data and trying to parse it, so raw user data can't be directly validated.
I was thinking about 422 Unprocessable Entity because it is related to validation even if is not directly the data (url) but the reference of this data (content of the url).
What is your opinion?
422 is inappropriate for #2 and #3. It relates to the server understanding the Content-Type header, but the actual content in the HTTP request body could not be interpreted.
I think you could make the argument that 502 Bad Gateway is appropriate here. It's a bit weird because the problem is both user error (incoming url parameter, so a 4xx code), but also it's kind of happening on the server, and in particular an origin server (which makes sense as a 5xx and specifically 502).
But if in this context you strictly consider this an issue that the client caused (bad input in the url) and not server-side, then I would say that there's not a specific enough error code for this, and you should probably just stick to 400 for all of them.
And maybe.. perhaps you can make the argument that 409 might work here. A 409 can used in a case where:
There is nothing in particular wrong with the HTTP request perse.
But the state of another resource is causing the request to fail.
Typically that 'other resource' lives in the same system, but I don't see why the external Atom feed could also not be considered as conflicting.
Because if the Atom feed on the external server is 'fixed', then the original HTTP request that the user made will now work. So a 409 kind of is appropriate here.

Long GET request on REST API, handling server crashes

I have a REST API where the GET request can take 10-20 seconds. So I usually return a 202 code with a location like http://fakeserver/pending/blah where the client can check the status of this request. pending/blah returns a 200 code with "Status: pending" if the request is still pending, and a 303 code when it's done, with a final location for the result: http://fakeserver/finished/blah .
But what if the server crashes during the request processing? Should pending/blah return a 303 code, and then finished/blah returns a 404? How can I alert the client that the resource may be available at a location, but I'm not sure? Assume the requests are persistent, so that when the server reboots, it continues processing the request.
First of all I'll make the state of processed resource an internal field of this resource. This way you can avoid using strange endpoints like: /finished/blah/ or /pending/blah/ and instead of it introduce a single endpoint /resources/blah/ which will among other fields return the state it's currently in.
After changing architecture to the endpoint mentioned above if you ask for blah and server has crashed you can:
return 200 with pending status - client doesn't have necessarily to know about the crash
return 404, simple not found with and extra message that server has crashed.
return 500 and inform the client explicitly what the problem is.
Other useful codes may be also 409 or 503. Returning any 3XX is not a good idea IMO since no redirection applies here. Personally I'd go for 200 or 500(3).

Picking HTTP status codes for errors from REST-ful services

When a client invokes my REST-ful service, it needs to know if the response came back was 'from me' or rather a diagnosis from the containing web server that something awful happened.
One theory is that, if my code is called, it should always return an HTTP OK(=200), and any errors I've got to return should be just represented in the data I return. After all, it's my code that gets the response, not the naked browser.
Somewhat self-evidently, if I'm using REST to generate HTML read directly by a browser, I absolutely must return an error code if there's an error. In the case I care about, it's always Javascript or Java that is interpreting the entrails of the response.
Another possibility is that there is some family of HTTP status codes that I could return with a high confidence that it/they would never be generated by a problem in the surrounding container. Is this the case?
I use the following:
GET
200 OK
400 Bad Request (when input criteria not correct)
POST
202 Accepted (returned by authorization method)
401 Unauthorized (also returned by authorization)
201 Created (when creating a new resource; I also set the location header)
400 Bad Request (when data for creating new entity is invalid or transaction rollback)
PUT
Same as POST
201 Ok
400 Bad Request
DELETE
200 OK
404 Not Found (same as GET)
I would not know how to avoid that some container returns codes like 404.
4xx codes are meant to handle client errors along with possibly some entity that describes the problem in detail (and thus would mean a combination of both of your mentioned approaches). Since REST relies on HTTP and the according semantics of status as well as methods, always returning 200 in any possible case is a violation of this principle in my opinion.
If you for instance have a request such as http://foo.com/bar/123 which represents a bar ressource with id=123 and you return 200 with some content, the client has no chance to figure out if this was the intended response or some sort of error that occured. Therefore one should try to map error conditions to status codes as discussed in REST: Mapping application errors to HTTP Status codes for example.

When is it appropriate to respond with a HTTP 412 error?

It is unclear to me when you should and should not return a HTTP 412: Precondition Failed, error for a web service? I am thinking of using it when validating data. For example, if a client POST's XML data and that data is missing a required data element, then responding with a 412 and a description of the error.
Does that align with the spirit of responding with an HTTP 412, or should something else be used (e.g. another http error code or web application exception)?
If you look at RFC 2616 you'll see a number of request headers that can be used to apply conditions to a request:
If-Match
If-Modified-Since
If-None-Match
If-Range
If-Unmodified-Since
These headers contain 'preconditions', allowing the client to tell the server to only complete the request if certain conditions are met. For example, you use a PUT request to update the state of a resource, but you only want the PUT to be actioned if the resource has not been modified by someone else since your most recent GET.
The response status code 412 (Precondition Failed) is typically used when these preconditions fail.
Your example sounds like an invalid request (i.e. the client has submitted data that is invalid because of missing values). A status code of 400 (Bad Request) is more appropriate here IMO.
412 is reserved for cases where the request is conditional, and the condition isn't met.
For your use case, 422 Unprocessable Entity is a good match.
Your best bet would be to avoid 412. In practice most web services that I've used send a 400 code (Bad Request). A lot of frameworks have built-in support for 400 too and your clients will appreciate a more common error code. Often times, especially with REST interfaces, a simple "message" or "error" element is returned with a description.