Difference between PUT and POST in Java REST API

1. Introduction

In the context of Java REST APIs, PUT and POST are HTTP methods used to send data to the server. PUT is typically used to update a resource entirely or create a resource if it does not exist and the client is specifying the resource ID. POST, on the other hand, is used to create a new resource without the client specifying the resource ID, or to trigger operations that do not necessarily create resources.

2. Key Points

1. PUT is idempotent, meaning multiple identical requests should have the same effect as a single request.

2. POST is not idempotent, and making multiple identical requests will typically result in different outcomes.

3. PUT replaces the entire resource or creates a new one if it doesn’t exist at the specified URL.

4. POST is used to create a new resource or submit data to the server for processing.

3. Differences

PUT POST
Used to update or create a resource at a specific URL. Used to create a new resource or process data.
Idempotent: subsequent calls with the same data do not change the outcome. Not idempotent: subsequent calls might produce new resources or different outcomes.
The client specifies the URI for the resource. The server controls the final URI of the new resource.

4. Example

// PUT example to update user details
@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> updateUser(@PathVariable("id") String id, @RequestBody User user) {
    // Code to update the user
    return new ResponseEntity<>("User is updated successsfully", HttpStatus.OK);
}

// POST example to create a new user
@RequestMapping(value = "/users", method = RequestMethod.POST)
public ResponseEntity<Object> createUser(@RequestBody User user) {
    // Code to create a new user
    return new ResponseEntity<>("User is created successfully", HttpStatus.CREATED);
}

Output:

// Response for PUT request
HTTP/1.1 200 OK
User is updated successfully
// Response for POST request
HTTP/1.1 201 Created
User is created successfully

Explanation:

1. The PUT example is a request mapping in a Spring controller that updates a user's details based on the provided ID. It's idempotent because if you call it multiple times, the user details will be updated only once.

2. The POST example is a request mapping in a Spring controller that creates a new user. It's not idempotent because calling it multiple times will create multiple users.

5. When to use?

- Use PUT when you want to update a resource or create a new resource at a specific URL, and subsequent identical requests should have no additional effect.

- Use POST when you want to create a new resource without specifying the URL or to submit data for processing to the server where the operation might result in the creation of a new resource.

Comments