Swift: check for successful HTTP status code [closed] - swift

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 2 years ago.
Improve this question
I'd like to see if an HTTPURLResponse statusCode begins with 2 to indicate success. Does it make more sense to see if it falls between 200 and 299, inclusive? Or does Swift have a builtin function to see if an HTTP status code represents success?
That is, given,
var statusCode: Int = ..
which, if any, of the following expressions would be preferred?
let success = String(statusCode).prefix(1) == "2"
let success = statusCode < 300 && statusCode >= 200
The relevant documentation reads,
The first digit of the Status-Code defines the class of response. The
last two digits do not have any categorization role. There are 5
values for the first digit:
- 1xx: Informational - Request received, continuing process
- 2xx: Success - The action was successfully received,
understood, and accepted
- 3xx: Redirection - Further action must be taken in order to
complete the request
- 4xx: Client Error - The request contains bad syntax or cannot
be fulfilled
- 5xx: Server Error - The server failed to fulfill an apparently
valid request
https://www.ietf.org/rfc/rfc2616.txt

You are right that anything between 200 and 299 (inclusive) means success.
However, it's not a complete picture. A 3XX response might mean that you don't know if the request is successful yet, and you need to follow the redirect to find out what the real status was.
A 303 redirect can lead to a URI that returns a 404, or a 200 OK.

Related

Identical HTTP GET has status 200 on first request but 304 after that [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
I'm confused with Status Code 304 "The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources", what does retransmit the requested resources refers to?
Context:
I'm using JSON SERVER to mock the back-end
Every time I request for the url the first time, it would be okay (200)
The following requests would result to status 304
The description of HTTP 304 sounds very vague to me, why would it say there's no need to retransmit the requested resources when I didn't cache the data originated from db.json in the first place.
Client code:
fetch(`http://localhost:4000/profiles`)
.then(res => res.json())
.then(data => setProfiles(data));
Server log:
GET /profiles 200 1.970ms - - # The first request is status 200
GET /profiles 304 2.609ms - - # The subsequent requests are status 304
GET /profiles 304 2.951ms - -
GET /profiles 304 2.903ms - -
# ...
To rephrase "the HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources":
You request a resource (the data from /profiles) once, and the server sends you that data with a 200 OK status. Now when you request the same resource (/profiles) and its data hasn't changed from the first request, the server will respond with a 304 Not Modified since it assumes you already have the data — it hasn't been modified since the request that was 200 OK.
You say you didn't cache the data in the first request but the server is assuming you would (like the MDN docs for 304 Not Modified say, "It is an implicit redirection to a cached resource") and is trying to save resources.
You'll have to determine if it's best in your specific situation to
cache the first response,
read a possible Expires header and only rerequest after that moment in time, or
possibly omit an If-None-Match ETag header as to tell the server that you don't have a cached version of the resource to use

HTTP Error Code while trying to change an immutable object?

I have a quiz in which I can give an answer to a question over a restful API. The request will transmit the answer to the question over a PUT-Request to an URL like “/question/{id}/answer”. But each question can only be answered once. The answer can be queried over a get request but can never be changed again. What HTTP Error Code do I return when the client tries to change the immutable answer with a PUT request?
I tried this error codes:
405 Method Not Allowed: But in the first place a PUT is fine. But once the object is set a PUT is not allowed anymore. Is it OK if the list of allowed methods change over time?
409 Conflict: Would work, but the RfC says “his code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.” And here the client would not be able to resolve the conflict.
400 Bad Request: It is in general a bad request but not “due to malformed syntax.”
So, is it a Server Error (5xx)? In case of a 500 Internal Server Error the RfC states that “The server encountered an unexpected condition”. But we expect the object to become immutable at some point.
Is it OK if the list of allowed methods change over time?
Yes.
Allow header field in a 405 response containing a list of the target resource's currently supported methods. -- RFC 7231
Note: currently supported methods....

If a Restful webservice fails to update or create a resource with PUT or POST methods respectively. What should be the response code?

If a Restful webservice fails to update or create a resource with PUT or POST methods respectively, what should be the response code?
Should the response code for failure of PUT and POST methods be in the 200 or 500 range. And what should be the exact code and possible response message.
Edit: extending the question to GET and DELETE also
And similarly what should be the failure code for unsuccessful GET and DELETE requests.
Ex: GET /profiles/lincoln - refers to existing profile - so returns 200 response code(correct me if wrong).
but GET /profiles/mccain - refers to not existing profiles - so what should be response code
And similarly for delete -
Ex: DELETE /movies/starwars - refer to existing movie so delete is successful (not sure what the success response code should be for delete - plz comment)
but: DELETE /movies/planetofhumans - refers to non - existing movie. so what should be the response code.
Stop making it hard.
The semantics are described in RFC 7231
if the request contains bad syntax or cannot be fulfilled: return a status from the 4xx (Client Error) class
if the server failed to fulfill an apparently valid request: return a status from the 5xx (Server Error) class
The actual method specified in the request doesn't matter: they all use the same semantics for each of the status codes.
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
You can use any media type you like for that representation - web sites have been using HTML for years. If you are looking for something JSON specific, then Problem Details for HTTP APIs may be a good choice.
GET /profiles/mccain - refers to not existing profiles - so what should be response code
404 NOT FOUND
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Is there a way to get the "Response Body" in the test results of Postman collection [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I have Postman collection to run POST request 10 iterations, in each iteration I have different values for the variables in the request body, and I am doing that by using CSV.
After completing running the collection, I cannot see the "Response Body" for each iteration. it shows data for the test results and statistics, but not for the actual response body.
Is there any idea to how I can get the response body for each request/iteration in the collection, is that not available in Postman, is there any other tools can do that?
More simplistic way is:
tests[`Response Body: ${responseBody}`] = true;
In the latest version (5.5.0) you can see the response data for each request by clicking on the request name in the Collection Runner. This will give you the details about the request made and the response received.
You can get the response body like this in your test section:
const body = pm.response.json();
Then you can print it in your test results as:
tests["Response Body ", body] = true;

What's the "correct" HTTP status code for valid request that fail for a valid business reason? [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 4 years ago.
Improve this question
Wanted to get your opinion on this, probably there's isn't an absolute right answer, but I want to see what you think is the more correct approach.
If there's nothing structurally wrong with a request (it's in the correct format) and all the fields are valid (field values not too long, required fields have a value etc...) but the call failed because of a business reason, for example "you cannot change a status of task that isn't assigned to you", what should be the response in this case:
200 with a JSON which explains the error:
{
error: {
code :120,
message: "you cannot change a status of a task that isn't assigned to you"
}
}
or maybe a 4xx response with a similar body:
{
error: {
code :120,
message: "you cannot change a status of a task that isn't assigned to you"
}
}
While I want to agree with #EJK, the spec he linked is out of date.
The most current one is RFC7231: https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1 which changed the meaning of the old 403 FORBIDDEN response status.
Answer:
So for the sake of this question 400 BadRequest should be used, because whoever consumed your service, case being the client, is wrong and can possible fix his request
The 400 (Bad Request) status code indicates that 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).
An example from your own use case:
The client now knows that the error "you cannot change a status of a task that isn't assigned to you" is his own fault. And he may even try to issue a different new (valid) request.
403 Forbidden seems like a good match.
From http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4.
The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated. If
the request method was not HEAD and the server wishes to make public
why the request has not been fulfilled, it SHOULD describe the reason
for the refusal in the entity. If the server does not wish to make
this information available to the client, the status code 404 (Not
Found) can be used instead.
Thus, option 2, as you have proposed, seems good as it also describes the reason for the failure.