Difference Between @PostMapping and @PutMapping in Spring Boot

🚀 Introduction: Understanding @PostMapping vs @PutMapping

In Spring Boot REST APIs, both @PostMapping and @PutMapping are used to send data to the server, but they serve different purposes.

Key Differences:

Feature @PostMapping @PutMapping
Purpose Used for creating a new resource. Used for updating an existing resource (full update).
Idempotency Not idempotent (multiple calls create multiple resources). Idempotent (multiple calls result in the same update).
Request Body Contains new resource data (may or may not have an ID). Contains the complete updated resource with an ID.
Response Status 201 Created when a resource is successfully created. 200 OK or 204 No Content when updated successfully.
Common Usage Submitting forms, adding new records. Updating user details, modifying existing records.

1️⃣ Understanding @PostMapping in Spring Boot

📌 Use @PostMapping for creating a new resource.
✔ The server generates a unique identifier (ID) for the new resource.
Not idempotent – calling it multiple times creates multiple records.
✔ Returns 201 Created along with the new resource.

Example: Using @PostMapping for Creating a Resource

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User savedUser = userService.saveUser(user);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
    }
}

📌 Request (Creating a New User with POST)

{
  "name": "Ramesh",
  "email": "ramesh@example.com"
}

📌 Response (201 Created)

{
  "id": 1,
  "name": "Ramesh",
  "email": "ramesh@example.com"
}

The server assigns an ID (1) to the new user.
Multiple requests create multiple new users.

2️⃣ Understanding @PutMapping in Spring Boot

📌 Use @PutMapping for updating an existing resource.
✔ The request must contain the full updated object (including an ID).
Idempotent – multiple identical requests result in the same update.
✔ Returns 200 OK or 204 No Content when successful.

Example: Using @PutMapping for Updating a Resource

@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
    User updatedUser = userService.updateUser(id, user);
    return ResponseEntity.ok(updatedUser);
}

📌 Request (Updating an Existing User with PUT)

{
  "id": 1,
  "name": "Ramesh Updated",
  "email": "ramesh.new@example.com"
}

📌 Response (200 OK)

{
  "id": 1,
  "name": "Ramesh Updated",
  "email": "ramesh.new@example.com"
}

Updates the existing user (id=1) without creating a new one.
If the resource does not exist, the API should return 404 Not Found.

3️⃣ Key Differences Between @PostMapping and @PutMapping

Feature @PostMapping @PutMapping
HTTP Method POST PUT
Operation Type Creates a new resource. Updates an existing resource.
Idempotency Not idempotent (creates new resource every time). Idempotent (multiple requests have the same effect).
Request Body May not contain an ID (ID is generated by the server). Must contain an existing ID (resource to be updated).
Response Status 201 Created 200 OK or 204 No Content
Common Use Case Creating users, adding products. Updating user details, modifying existing products.

📌 Best Practice:
✔ Use @PostMapping for creating new resources.
✔ Use @PutMapping for updating existing resources.

4️⃣ Handling Updates with @PutMapping

Handling Non-Existing Resources in PUT

If the resource does not exist, the API should return 404 Not Found.

@PutMapping("/{id}")
public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
    if (!userService.existsById(id)) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
    }
    User updatedUser = userService.updateUser(id, user);
    return ResponseEntity.ok(updatedUser);
}

📌 If the user does not exist (id=5)

PUT /api/users/5

📌 Response (404 Not Found)

{
  "error": "User not found"
}

Ensures proper error handling when updating non-existing resources.

5️⃣ When to Use @PostMapping vs @PutMapping?

Use Case Use @PostMapping Use @PutMapping
Creating a new resource ✅ Yes ❌ No
Updating an existing resource ❌ No ✅ Yes
Multiple calls create multiple records ✅ Yes ❌ No
Requires an ID in the request body ❌ No ✅ Yes
Returns 201 Created ✅ Yes ❌ No
Returns 200 OK or 204 No Content ❌ No ✅ Yes

📌 Best Practice:
✔ Use POST for creating resources.
✔ Use PUT for updating resources (full replacement).

6️⃣ REST API Best Practices for POST and PUT

When to Use POST (@PostMapping)

  • When creating new records in the database.
  • When the server assigns an ID to the resource.
  • When inserting a list of new items.

📌 Example Use Case: Creating a New Product

{
  "name": "Laptop",
  "price": 1000.0
}

New product is created, and an ID is assigned by the server.

When to Use PUT (@PutMapping)

  • When updating an existing record.
  • When the client sends the full object with an ID.
  • When ensuring multiple identical updates do not create duplicates.

📌 Example Use Case: Updating Product Price

{
  "id": 10,
  "name": "Laptop",
  "price": 900.0
}

Product ID 10 is updated, instead of creating a new one.

🎯 Summary: Best Practices for @PostMapping and @PutMapping

Use @PostMapping for creating new resources (server assigns an ID).
Use @PutMapping for updating existing resources (client provides an ID).
Ensure POST requests return 201 Created with the new resource.
Ensure PUT requests return 200 OK or 404 Not Found if the resource does not exist.
Use PUT for idempotent operations (multiple requests result in the same outcome).

🚀 Following these best practices ensures clean, maintainable RESTful APIs in Spring Boot!

SEO Keywords:

Spring Boot @PostMapping vs @PutMapping, difference between @PostMapping and @PutMapping, HTTP POST vs PUT, REST API best practices, Spring Boot CRUD operations

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare