Spring Boot – Write DELETE Methods

In this chapter, we would write the DELETE methods. It is similar to the GET method. However, in case of he DELETE, the nothing is returned. Therefore it is a void method. Also the DELETE method in the controller files takes a path variable.

  1. Write the deleteLocation Methods
  2. Write the deleteUser Methods
  3. Write the deletePost Methods
  4. Test the Application

 

1. Write the deleteLocation Methods

Open the LocationController file and write the deleteLocation method as shown below

 @RequestMapping(value = "/location/{id}", method = RequestMethod.DELETE)
 public void deleteLocation(@PathVariable String id) {
     locationService.deleteLocation(id);
 }

Listing 1.0: deleteLocation for the LocaitonController

 

After you write this code, you will have an error. So you need to add the deleteLocation method in the LocationService file as shown below

public void deleteLocation(String id) {
    locations.removeIf(t -> t.getId().equals(id));
}

Listing 1.1: deleteLocation for the LocationService class

 

 

2. Write the deleteUser Methods

Open the UserController file and write the deleteUser method as shown below

 @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
 public void deleteUser(@PathVariable String id) {
      userService.deleteUser(id);
 }

Listing 1.2: deleteUser for the UserController class

 

Similarly, add the deleteUser method in the UserService file as shown below

public void deleteUser(String id) {
     users.removeIf(u -> u.getId().equals(id));		
}

Listing 1.3: deleteUser for the UserService class

 

 

3. Write the deletePost Methods

Open the PostController file and write the updatedPost method as shown below.

 @RequestMapping(value = "/posts/{id}", method = RequestMethod.DELETE)
 public void deletePost(@PathVariable String id) {
     postService.deletePost(id);
 }

Listing 1.4: deletePost for the PostController class

 

Similarly, add the deletePost method in the LocationService file as shown below

public void deletePost(String id) {
     posts.removeIf(p -> p.getId().equals(id));		
}

Listing 1.5: deletePost for the postService class

 

 

4. Test the Application

Now, you can use Advanced REST Client to test the update methods.

You do it almost the same way as the GET methods. But this time you need to specify the id in the url as well.

After making the delete, you can then make a post request to confirm the delete worked.

I recommend you watch the video.