REST Controller & HTTP Methods
In a REST API, you interact with resources using HTTP methods. Think of them as verbs that tell the server what action to perform:
- GET – Retrieve data (like viewing a menu).
- POST – Create new data (like placing an order).
- PUT – Update entire resource (like changing your entire order).
- PATCH – Partial update (like changing only the drink).
- DELETE – Remove data (like canceling an order).
In Spring,
@RestController is a specialized version of @Controller that automatically serializes return objects to JSON/XML. You don't need @ResponseBody on each method.Here is a complete REST controller demonstrating all HTTP methods:
@RestController
@RequestMapping("/api/users")
public class UserController {
// In-memory list (instead of database)
private List users = new ArrayList<>();
private int nextId = 1;
// GET all users
@GetMapping
public List getAllUsers() {
return users;
}
// GET single user by ID
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) {
return users.stream()
.filter(user -> user.getId() == id)
.findFirst()
.orElseThrow(() -> new RuntimeException("User not found"));
}
// POST create new user
@PostMapping
public User createUser(@RequestBody User user) {
user.setId(nextId++);
users.add(user);
return user;
}
// PUT update entire user
@PutMapping("/{id}")
public User updateUser(@PathVariable int id, @RequestBody User userDetails) {
User user = getUserById(id);
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
user.setAge(userDetails.getAge());
return user;
}
// DELETE user
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id) {
users.removeIf(user -> user.getId() == id);
}
// PATCH partial update (only name)
@PatchMapping("/{id}")
public User partialUpdateUser(@PathVariable int id, @RequestBody Map updates) {
User user = getUserById(id);
if (updates.containsKey("name")) {
user.setName((String) updates.get("name"));
}
return user;
}
}
Key annotations used:
- @PathVariable – captures values from URL template (like id).
- @RequestBody – converts JSON request body to Java object.
- @GetMapping, @PostMapping etc. – shortcut for @RequestMapping.
Two Minute Drill
- @RestController = @Controller + @ResponseBody on every method.
- GET retrieves resources, POST creates, PUT updates fully, PATCH updates partially, DELETE removes.
- @PathVariable captures URL parameters.
- @RequestBody converts JSON to Java object.
- Always return proper HTTP status codes (we'll learn that next).
Need more clarification?
Drop us an email at career@quipoinfotech.com
