Programming & Development / March 27, 2025

How to Use @PutMapping with ResponseEntity in Spring Boot (with Example)

spring boot putmapping responseentity spring boot update rest api spring boot put request example spring rest api putmapping response status update entity spring boot rest spring boot return 404 if not found

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@PutMappingHandles PUT request to update dataResponseEntity<T>Controls HTTP status and response bodyHttpStatus.OKReturned if update is successfulHttpStatus.NOT_FOUNDReturned if the resource does not exist


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex