Learn how to build a REST API in Spring Boot using @PutMapping
and ResponseEntity
. This article walks through:
- Creating a
PUT
endpoint to update a resource - Using
ResponseEntity
to return HTTP 200 or 404 - Handling request data and in-memory persistence
- Returning JSON responses for successful and failed updates
Perfect for developers building RESTful services with proper status handling.
π§ Scenario: Update an Item via PUT Request
Letβs say weβre managing items using a REST API. You want to:
- Accept an updated
Item
via a PUT request - Return
200 OK
if updated successfully - Return
404 Not Found
if the item doesn't exist
β
Step 1: Create the Item
Class
java
public class Item {
private Long id;
private String name;
// Getters & Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
β
Step 2: Create the Service Layer
java
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class ItemService {
private Map<Long, Item> itemRepository = new HashMap<>();
public ItemService() {
// Seed data
itemRepository.put(1L, new Item() {{ setId(1L); setName("Item1"); }});
itemRepository.put(2L, new Item() {{ setId(2L); setName("Item2"); }});
}
public Item updateItem(Long id, Item item) {
if (itemRepository.containsKey(id)) {
item.setId(id); // Ensure consistent ID
itemRepository.put(id, item);
return item;
}
return null;
}
}
β
Step 3: Create the REST Controller
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/items")
public class ItemController {
@Autowired
private ItemService itemService;
@PutMapping("/{id}")
public ResponseEntity<Item> updateItem(@PathVariable Long id, @RequestBody Item item) {
Item updated = itemService.updateItem(id, item);
if (updated != null) {
return new ResponseEntity<>(updated, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
π‘ Example API Request
PUT Request to Update Item with ID 1
- URL:
http://localhost:8080/api/items/1
- Method:
PUT
- Body:
json
{
"name": "Updated Item Name"
}
π’ If Item Exists
Response:
json
{
"id": 1,
"name": "Updated Item Name"
}
Status Code: 200 OK
π΄ If Item Does Not Exist
Response:
css
(empty body)
Status Code: 404 Not Found
π Summary Table
ComponentDescription@PutMapping
Handles PUT request to update dataResponseEntity<T>
Controls HTTP status and response bodyHttpStatus.OK
Returned if update is successfulHttpStatus.NOT_FOUND
Returned if the resource does not exist