What to return when failing to update a resource via API request? The resource or an error? - http-status-codes

Suppose I'm trying to update a user via an API request to change his status to "active":
PUT http://example.com/user/12/activate
What should my request handler return if the user is already "active"? Should I return a 200 response with the unmodified user object as its content, or should I return a 500 response with an error description?
If I should return the user object, how can the client know that something went wrong? Should I use a status code other than 200?

You can return 409 Conflict HTTP status code in such cases.
You can learn about various HTTP status code using the links below:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409

Related

HTTP Status to return if resources are partially created in Spring boot - rest api?

I've a scenario where a post request from first microservice creates new user and creates a wallet for newly created user from different microservice.
I'm returning HTTP status 201 when both user and wallet created. I'm bit confused what status should I return if user is created but wallet isn't.
I came across some articles and found two relevant to my confusion but are contradictory on returning HTTP status 207 due to its limitation related to WebDAV.
Is Http response 207 MULTI-STATUS appropriate for multi task operations?
REST API response in partial success
refer my code -
#PostMapping("/register")
public ResponseEntity<User> saveUser(#RequestBody User user) {
user.setUserId(sequenceGeneratorService.generateSequence(User.SEQUENCE_NAME));
user.getRoles().forEach(role -> role.setRoleId(sequenceGeneratorService.generateSequence(Role.SEQUENCE_NAME)));
User savedUser = userService.saveUser(user);
ResponseEntity<Wallet> createdWallet = createUserWallet(savedUser);
if (createdWallet.getStatusCode().is2xxSuccessful()) {
savedUser.setWallet(createdWallet.getBody());
return new ResponseEntity<User>(savedUser, HttpStatus.CREATED);
} else {// here is the confusion
return new ResponseEntity<User>(savedUser, HttpStatus.MULTI_STATUS);
}
}
private ResponseEntity<Wallet> createUserWallet(User savedUser) {
Wallet userWallet = Wallet.builder()
.walletId(sequenceGeneratorService.generateSequence(Wallet.SEQUENCE_NAME))
.userId(savedUser.getUserId())
.balance(BigDecimal.ZERO).build();
return walletServiceProxy.createWallet(userWallet);
}
May I know which status should I return here?
I'm returning HTTP status 201 when both user and wallet created. I'm bit confused what status should I return if user is created but wallet isn't.
HTTP status codes are metadata of the transfer-of-documents-over-a-network domain (see Webber 2011); they are there so that general purpose HTTP components can correctly interpret the response, and do intelligent things (like invalidating previously cached responses, when appropriate).
Your HTTP API is a facade: a costume that your implementation wears that makes it look like an HTTP aware document store. (The fact that your implementation doesn't have "documents" is an implementation detail, hidden behind this facade.)
The responses you send should be understood in this same way - you are telling the HTTP client (and also any intermediary components who can read the response metadata) how your (imaginary) web page reacted to the request that was sent.
Was the message processed successfully? Did it create a new (imaginary) web page with its own identifier, that clients can send messages to? Then you should normally be sending back a 201 Created, even if the implementation didn't achieve that outcome via the "happy path".
On the other hand, if you want general purpose components to understand that request processing failed, you send a 4XX Client Error or a 5XX Server Error, as appropriate.
(You probably shouldn't be using 207 MultiStatus unless you are deliberately doing WebDav things and are expecting requests from WebDav aware components; it doesn't achieve anything useful unless the client implementation knows how to handle multistatus XML documents).
Reminder: the part of an HTTP response where you describe in detail what happened and how the end consumer can respond to it is the body of the HTTP response.
201 Created
Location: /users/12345
Content-Type: text/plain
Hey, we created the new user you asked us to. Isn't that great?
You can review the details of the user at: /users/12345
But, we weren't able to create a wallet for the user. If that's
kind of important to you, could you fill in this form and send it
to us: /lost-wallets#form ?
Thanks, and have a great day

Postman GET returning HTML and status 200

I am trying to call a Postman GET endpoint, and it is returning HTML and status 200, instead of a valid JSON response and status 200. It looks like it is not hitting the backend at all. I have a separate POST endpoint, which works fine and returns me a valid JSON response.
Could this be due to authorization headers? I am using the same authorization for both.
I managed to resolve the issue. I had to add a cookie header, which I got from the browser since I was able to call the service from the browser and I had authenticated on browser level.

Status 200 ok giving blank response

I am working on spring cloud project, getting status 200 ok status but the response body is empty for the APIs. Can any one help me to resolve the issue?
Thanks & Regards
Anita PAtil
Status is different from the Response vody. Response Body depends on what you are returning or binding any data to the Response Body. Know about HTTP Response status line, headers and body and the difference between them. The status here Indicates that Server accepted the request or there is an aasociated action method in the server to respond.

What is the HTTP status code to return when input data is missing?

I have written a REST API in nodejs.
I want to send HTTP status codes on various events.
For example when data is returned I send HTTP code 200.
What is the status code to return when the input data is missing?
This isn't specific to nodejs. HTTP status codes are general -- you can read about them on wikipedia:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
I think you want client error code 400, which means Bad Request.
Perhaps you should return 404, not found. As mentioned in previous answer, HTTP status codes are general.
A tip: try getting grip on HTTP before starting off web development.

REST API - best method for error handling

When constructing an API response, which method is better for (manually) returning the status code to indicate the validity of the request:
1 - Embed a response code within the JSON response
{
'status_code' => 200,
'status_message' => 'OK',
'data' => { ... }
}
2 - Or is it better to modify the HTTP Headers Status field?
Request URL:http://somesite.com
Request Method:GET
Status Code: 200 (EDITING THIS ONE)
I would think that the HTTP Statuses should only be regarding connection errors and file retrieval errors that occur at the server level rather than altering this to address application level errors.
Any good articles and resources to read would be very appreciated as well.
I have found the best way to present errors in a REST Request is to change the HTTP Status Code to the proper error, and embed the error in the response.
If you are using JSON, it might look like this, with the status code set to 500 for this example:
{"error" : "An error has occurred while trying to read from the database."}
This is the same method that Microsoft CRM uses to report errors, and it has proved to be a good method; RESTFul applications will not fail to parse the response if they are expecting JSON (or XML, if you are using that).
This question addresses the same issue (perhaps from a slightly different perspective).
I think that, in general, if a request to a resource in your application results in an error condition, that fact should be reflected in the HTTP headers. You can use the application response to provide more detailed information.
Update: Here is an interesting mapping of application errors to status codes (used by Azure).

Resources