DELETE

Handle a DELETE request with @DeleteMapping, taking the category's id from the URL, and answer 204 No Content.

Journeyman · Spring Boot · REST API · Updated

By

Deleting a record should be done through a DELETE request. When a client DELETEs a record - the id should be included in the URL

A DELETE request is a header only: the verb DELETE and the address of the category, /categories/10

The server will delete the data, then it will return a status of no content (204).

The server answers 204 (no content), with no body

DELETE Request - Client

In Insomnia, this is your Delete Snacks request from Insomnia: DELETE, with no body:

DELETE {{ _.base_url }}/api/categories/10

DELETE Request - Server

The method responsible for handling the request must be marked with a @DeleteMapping annotation to handle the request. The id of the resource must be marked as a @PathVariable. The @ResponseStatus annotation specifies the status code that will be returned (HttpStatus.NO_CONTENT returns a status of 204)

@DeleteMapping(path="/api/categories/{id}")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void deleteCategory(@PathVariable int id)
{
    // the DAO deletes the row; nothing is returned
    categoryDao.delete(id);
}

DELETE Response - Client

Add the method to your controller and the delete method to your DAO, run the app again, and send Delete Snacks. The 405 Method Not Allowed from Insomnia: DELETE is now 204 No Content, and the body is empty. Then send All categories: category 10 is gone from the list.

Insomnia shows 204 No Content and an empty body after DELETE /api/categories/10

Do it: delete a category from a list, the way the DAO does

The DELETE method asks the DAO to delete the category with the address's id, and answers 204 either way. Write that delete for a list of categories instead of a database.

Category is given at the bottom of the file, with getCategoryId() and getCategoryName().

The method gets two values:

  • categories: the saved categories, a List<Category>.
  • id: the id from the address, an int, such as 10 from DELETE /api/categories/10.

For example, the list holds Beverages (1), Seafood (8) and Snacks (10), and a client sends DELETE /api/categories/10:

Step Here
Find the category whose id is 10 Snacks, at index 2
Remove it 1 removed
The list now holds Beverages and Seafood

So after delete(categories, 10), the list holds Beverages and Seafood.

Your job: write the method delete(List<Category> categories, int id). It returns nothing (void): it changes the list.

  • Remove the category whose id is id from the list.
  • Leave the other categories in their order.
  • When no category has that id, leave the list as it is: deleting something that isn't there is not an error, as the API's second 204 shows.

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

Cheat sheets