Distinguishing @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping in Spring MVC

Alexander Obregon
4 min readAug 22, 2023
Image Source

Introduction

The Java ecosystem has always been vibrant when it comes to frameworks for building web applications. Among them, Spring MVC stands out for its strength and ease of integration with other technologies. A key aspect of Spring MVC is its annotation-driven nature, which makes it intuitive to handle HTTP requests.

In this article, we’ll look into understanding four commonly used annotations in Spring MVC for HTTP operations: @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping.

An Overview of HTTP Methods

Before delving into the annotations themselves, it’s essential to understand the HTTP methods they represent:

  • GET: Fetches data. It is safe and idempotent, which means repeated requests produce the same result. It only retrieves data and has no other side effects.
  • POST: Submits data to be processed. It’s neither safe nor idempotent. Typically used for creating resources.
  • PUT: Updates or creates data. Idempotent but not safe. Typically used for updating existing resources or creating them if they don’t exist.
  • DELETE: Removes data. Idempotent but not safe. Used for deleting resources.

@GetMapping

This annotation is a shortcut for @RequestMapping(method = RequestMethod.GET).

When you want to handle a GET request, you use @GetMapping.

Example:

@RestController
public class UserController {

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
// Logic to fetch a user by id
return userService.getUserById(id);
}
}

@PostMapping

This is an alternative to @RequestMapping(method = RequestMethod.POST).

Used mainly for creating new resources.

Example:

@RestController
public class UserController {

@PostMapping("/users")
public User createUser(@RequestBody User user) {
// Logic to save a user
return userService.saveUser(user);
}
}

@DeleteMapping

A shorthand for @RequestMapping(method = RequestMethod.DELETE).

This annotation is utilized when you want to delete a specific resource.

Example:

@RestController
public class UserController {

@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
// Logic to delete a user by id
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}

Benefits of Using These Annotations

  1. Readability: One of the most significant benefits of these annotations is the clarity they bring to your code. With the use of @GetMapping, @PostMapping, etc., anyone reviewing your code can quickly identify the type of HTTP operation being handled. Traditional methods like using @RequestMapping with the method attribute can be more verbose and challenging to decipher at a glance. With these streamlined annotations, the intent of the endpoint is immediately apparent, making your code more self-documenting.
  2. Less Room for Error: Simplifying your annotations means fewer chances for mistakes. Using a specific annotation for each HTTP method ensures that there’s no ambiguity. It’s easy to overlook or make mistakes when you’re dealing with multiple parameters in the @RequestMapping annotation. By using specific method annotations, you're making sure each controller method is dedicated to a single, specific HTTP action.
  3. Ergonomics: Developers love clean and concise code. These annotations encapsulate the intent neatly, which means you spend less time setting up and more time focusing on your business logic. This reduction in boilerplate is not only aesthetic; it can lead to faster development cycles and fewer errors introduced during the process.
  4. Consistency: By adopting these annotations, you introduce a level of consistency in your codebase. This makes it easier for teams to collaborate. When everyone follows the same approach, it reduces cognitive load and accelerates the onboarding process for new team members. They know what to expect when navigating the codebase, leading to quicker understanding and fewer miscommunications.
  5. Flexibility with Other Annotations: These HTTP method annotations seamlessly work alongside other Spring MVC annotations. This means you can effortlessly combine them with annotations like @ResponseStatus, @PathVariable, or @RequestBody, allowing for powerful combinations while keeping the code tidy and understandable.
  6. Better Tool Support: Modern Integrated Development Environments (IDEs) and other tools have better support for these specific annotations. They can provide relevant suggestions, better error highlighting, and even auto-generation capabilities based on the annotation used, making the developer’s life easier and more productive.
  7. Evolution of Best Practices: Adopting these annotations is in line with the evolving best practices in the Spring community. By staying updated and incorporating these newer conventions, your application remains modern, easier to maintain, and future-proof.

Incorporating these annotations isn’t just about writing less code; it’s about writing smarter, clearer, and more maintainable code. When your annotations communicate intent clearly, it aids both the current development and future maintenance, making the whole development lifecycle more efficient.

Combining Annotations

Remember, these annotations are merely shortcuts. They can be combined with other annotations to achieve more specific behaviors. For example, you can combine @PostMapping with @ResponseStatus to indicate a specific HTTP status code should be returned:

@PostMapping("/users")
@ResponseStatus(HttpStatus.CREATED)
public User createUser(@RequestBody User user) {
return userService.saveUser(user);
}

Conclusion

Understanding the nuances of @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping is fundamental to mastering Spring MVC. These annotations not only streamline your codebase but also make your endpoints more intuitive. Embrace them, and your journey with Spring MVC will be a smoother one.

Remember, while these annotations are powerful, they’re only a part of the vast suite of tools that Spring MVC offers. Always be on the lookout for ways to optimize and make your code cleaner and more efficient!

  1. Spring MVC Documentation
  2. Baeldung Spring MVC
Spring Boot icon by Icons8

--

--

Alexander Obregon

Software Engineer, fervent coder & writer. Devoted to learning & assisting others. Connect on LinkedIn: https://www.linkedin.com/in/alexander-obregon-97849b229/