Search code examples
springrestcontrollerhttp-status-codes

REST Controller class delete method responseType for object is null


I have a below method in my rest controller class

@DeleteMapping("/delete/{id}")
public ResponseEntity<?> deleteMovieById(@PathVariable Integer id) {
    try {
        service.deleteMovieById(id);
        responseEntity = new ResponseEntity<String>("Movie Deleted", HttpStatus.OK);
    } catch (MovieNotFoundException e) {
        **//Confused over here**
    } catch (Exception e) {
        responseEntity = new ResponseEntity<String>("Unable delete movie", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return responseEntity;
}

I have confused lot what should be response code if Movie Object Not Found while delete a movie

  1. NOT FOUND (404): usually we use it for URI/URL not found but here URL/URI is correct only requesting my content(movie id) only not in database.
  2. I see NOT FOUND(404) used in many examples even for no content matching.
  3. In this 404 is the right option then when to use 204(No Content)?

So anyone give me clear picture about these


Solution

  • I think 404 is definitely the right approach. The client is trying to do something to a specific resource. In this case DELETE it. When the resource cannot be found and therefore the delete can not be executed the only clear response to me seems a 404.

    After all 404 is a client error that specifies that the resource the client is referring too cannot be found, but otherwise the request itself is valid.

    204 means the server succesfully processed the request but returned no content. However the resource was not succesfully deleted because it was never found. So 204 is not applicable.