Learn

So far, you have:

  • Used a POST endpoint to Create a database entry
  • Used a GET endpoint to Read database entries
  • Used a PUT endpoint to Update a database entry

Sounds like you’re just one capability away from having a full-fledged CRUD application!

Implementing a DELETE endpoint that can Delete a database entry is straightforward. The CrudRepository offers a delete method that accepts the instance of the model that you wish to delete. For the Person example, this looks like:

@DeleteMapping("/people/{id}") public Person deletePerson(@PathVariable("id") Integer id) { Optional<Person> personToDeleteOptional = this.personRepository.findById(id); if (!personToDeleteOptional.isPresent()) { return null; } Person personToDelete = personToDeleteOptional.get(); this.personRepository.delete(personToDelete); return personToDelete; }

Notice that the .delete method differs slightly from the .save method that we have seen, in that it does not return anything. Instead of depending on the output of the .delete method to give a response back to the user of the API, we capture the object before it is deleted using .findById, and return that object to the user after the personToDelete has been deleted.

As was the case for getting and updating a plant by ID, we should use the Optional methods to check to see if the id supplied was valid, and terminate the method early by returning null if it was not present in the database.

Instructions

1.

Implement a similar method and endpoint that will allow a user to delete a Plant using a DELETE request to the "/plants/{id}" endpoint. Call this method deletePlant. The deletePlant method should accept an Integer id as a path parameter.

Your method should find the plant using the supplied id, and store the result in a variable plantToDeleteOptional.

Your method should perform the correct checks to ensure that the id supplied was valid. If not, terminate the method early by returning null.

If the id was valid, save the underlying Plant in a variable plantToDelete.

Next, it should call the correct method from the plantRepository to delete the instance of the model that was found.

Lastly, it should return the deleted Plant object to the user in the response body.

Ensure that you attach the correct Spring annotations!

2.

Validate your deletePlant functionality using curl. Delete the "Cherry Tree" from the plant database.

Remember, you can always use the GET /plants endpoint if you don’t know the id of the entry you wish to delete.

After you’ve made the delete request, validate that it is no longer in the database using the GET /plants endpoint again.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?