0
0
SpringbootDebug / FixBeginner · 4 min read

How to Handle PUT Request in Spring Boot: Simple Guide

To handle a PUT request in Spring Boot, create a controller method annotated with @PutMapping and accept the updated data as a method parameter. Use @RequestBody to bind the incoming JSON to a Java object, then update the resource accordingly.
🔍

Why This Happens

Developers often forget to use @PutMapping or @RequestBody in their controller method, causing Spring Boot not to recognize the PUT request or fail to bind the request data. This leads to errors like 405 Method Not Allowed or empty request body.

java
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    // Missing @RequestBody causes binding failure
    @PutMapping("/users/{id}")
    public String updateUser(@RequestBody User user) {
        // update logic
        return "User updated";
    }
}
Output
HTTP 400 Bad Request or 405 Method Not Allowed error due to missing @RequestBody or incorrect mapping
🔧

The Fix

Use @PutMapping to map the PUT request and @RequestBody to bind the JSON payload to a Java object. Also, include @PathVariable if you need to get the resource ID from the URL.

java
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @PutMapping("/users/{id}")
    public String updateUser(@PathVariable Long id, @RequestBody User user) {
        // update user with id using data from user object
        return "User with id " + id + " updated successfully";
    }
}
Output
User with id 1 updated successfully (when PUT /users/1 with JSON body is called)
🛡️

Prevention

Always use @PutMapping for PUT requests and @RequestBody to receive JSON data. Validate your request mappings and test with tools like Postman. Use clear method signatures and keep your API consistent.

Enable logging to catch mapping errors early and write integration tests for your endpoints.

⚠️

Related Errors

  • 405 Method Not Allowed: Happens if you use @GetMapping or @PostMapping instead of @PutMapping.
  • 400 Bad Request: Occurs when @RequestBody is missing or JSON format is invalid.
  • Missing Path Variable: Forgetting @PathVariable annotation causes errors when URL contains variables.

Key Takeaways

Use @PutMapping to handle PUT requests in Spring Boot controllers.
Annotate method parameters with @RequestBody to bind JSON request data.
Include @PathVariable to capture URL path parameters when needed.
Test your endpoints with tools like Postman to verify correct behavior.
Enable logging and write tests to catch mapping and binding errors early.