Returning ResponseEntity<T>

Return a ResponseEntity from a controller method to choose the status code, for example 404 when a category isn't found and 500 when something fails.

Journeyman · Spring Boot · REST API · Updated

By

When the server returns a response, it always includes header information. We can more easily control what is included in the header by returning a ResponseEntity object from our API calls.

public List<Category> getAllCategories()
{
    return categoryDao.getAllCategories();
}

Change it to return a ResponseEntity:

public ResponseEntity<List<Category>> getAllCategories()
{
    return ResponseEntity.ok(categoryDao.getAllCategories());
}

The response entity is a container that holds the response body and the status code that is to be returned.

Now, we can add logic to our controller methods, which determine which status code to return.

Adding a 404 Not Found Status

@GetMapping("/api/categories/{id}")
public ResponseEntity<Category> getCategory(@PathVariable int id)
{
    var category = categoryDao.getCategoryById(id);

    if(category == null)
    {
        return ResponseEntity.notFound().build();
    }

    return ResponseEntity.ok(category);
}

Adding Server Error Message

We should also handle general exceptions so that our response does not expose the details of our API when an error occurs.

@GetMapping("/api/categories/{id}")
public ResponseEntity<Category> getCategory(@PathVariable int id)
{
    try
    {
        var category = categoryDao.getCategoryById(id);
        if(category == null)
        {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(category);
    }
    catch (Exception e)
    {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                     .build();
    }
}

Do it: answer 404 when there's nothing to delete

Insomnia: DELETE showed that Delete Snacks answers 204 even the second time, when there was nothing left to delete. Many APIs answer 404 Not Found then. Change deleteCategory so it chooses its status code with a ResponseEntity, the way getCategory does above.

The DAO's delete now says how many rows it deleted: 1 when the category was there, 0 when it wasn't. (A JdbcTemplate's update gives that number back.)

The box has no Spring, so the bottom of the file has small stand-ins for Spring's HttpStatus and ResponseEntity, with the same names and the parts this lesson uses: ResponseEntity.noContent().build(), ResponseEntity.notFound().build() and ResponseEntity.status(...).build(). Leave them as they are. The annotations (@DeleteMapping, @PathVariable) are left out too.

The method gets one value:

  • id: the id from the address, an int, such as 10 from DELETE /api/categories/10.

For example, Delete Snacks sent a second time:

Step Here
categoryDao.delete(10) returns 0: no row had the id 10
The answer 404 Not Found

So when the DAO deletes 0 rows, deleteCategory(10).getStatusCode() is HttpStatus.NOT_FOUND.

Your job: change deleteCategory(int id) in CategoriesController so it returns a ResponseEntity<Void> with the right status.

  • Ask the DAO to delete the category with that id.
  • When it deleted a row (1), answer 204 No Content.
  • When it deleted no rows (0), answer 404 Not Found.
  • When the DAO throws an exception, answer 500 Internal Server Error, without the exception's details.
  • None of the answers has a body.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets