I was using HttpStatus.OK for all of my requests in Spring Bot Controller. But I realized that it is good to return a proper Http status and started to use the followings:
GET --> Ok
POST -> Created
PUT --> Ok ???
DELETE --> NoContent ???
But I am not sure regarding to PUT and DELETE, some people suggest using NoContent for DELETE and Ok for PUT. But I am confused and no idea which one is suitable.
So, which Status codes should I use for PUT and DELETE ? Here is an example usage for my DELETE, but I am not sure if we can return body when Status code is NoContent (is it meaningful?)
@DeleteMapping("/categories/{id}")
public ResponseEntity<ApiResponse<CommandResponse>> deleteById(@PathVariable long id) {
final CommandResponse response = categoryService.deleteById(id);
return ResponseEntity
.status(HttpStatus.NO_CONTENT)
.body(new ApiResponse<>(Instant.now(clock).toEpochMilli(), SUCCESS, response));
}
Update: Based on the situatin, I think the following implementations are ok:
#1:
@DeleteMapping("/categories/{id}")
public ResponseEntity<ApiResponse<Void>> deleteById(@PathVariable long id) {
categoryService.deleteById(id);
return ResponseEntity.ok(new ApiResponse<>(Instant.now(clock).toEpochMilli(), SUCCESS));
}
#2:
@DeleteMapping("/categories/{id}")
public ResponseEntity<ApiResponse<Void>> deleteById(@PathVariable long id) {
categoryService.deleteById(id);
return ResponseEntity
.status(HttpStatus.NO_CONTENT)
.build();
}
As described in Http Protocol RFC 2616
9.6 PUT
If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.
Also
9.7 DELETE
A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.
Edit: To clarify. The part in delete operation that describes the status 200 (OK) expects an entity not of the actual business deleted or not in database, but another object entity which is able to describe the status of the delete action (DONE, PENDING, FAILED...).