Open In App

What is the Difference Between PUT, POST, and PATCH in RESTful API?

Improve
Improve
Like Article
Like
Save
Share
Report

In the context of RESTful web services, HTTP defines several methods for manipulating resources. The most commonly used methods are POST, PUT, and PATCH.

POST

The POST method is used to submit an entity to a resource. It is used for creating a new resource or adding a new entity to an existing resource. When a POST request is sent, the server creates a new resource and assigns a new URL to it. 

Example: When creating a new user, a POST request can be sent to the /users endpoint with the user data in the request body.

The structure of a POST request in HTTP typically includes the following elements:

  • Request line: The first line of the request contains the HTTP method (POST), the resource path, and the HTTP version.
  • Headers: Headers provide additional information about the request, such as content type, encoding, and authentication credentials.
  • Request body: The body of the POST request contains the data to be submitted to the server, which can be in a variety of formats such as JSON, XML, or form data. The format of the data should be specified in the Content-Type header.

Here is an example of the basic structure of a POST request:

Java




POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
  
{
  "name": "Rahul Chauhan",
  "email": "rahulchauhan@gmail.com",
  "password": "password@123"
}


In the above example, the POST request is being sent to the /api/users endpoint on the example.com server. The content type of the request body is specified as application/json, and the body contains a JSON object with the user’s name, email, and password.

It’s worth noting that the request body in a POST request is optional, but it’s typically used to submit data to the server for processing, such as creating a new resource or updating an existing one.

PUT

The PUT method is used to update a resource or create a new resource if it does not exist. When a PUT request is sent, the entire resource is replaced with the new data. If the resource does not exist, it will be created.

Example: To update the information of a user with id 123, a PUT request can be sent to the /users/123 endpoints with the updated user data in the request body.

The structure of a PUT request in HTTP typically includes the following elements:

  • Request line: The first line of the request contains the HTTP method (PUT), the resource path, and the HTTP version.
  • Headers: Headers provide additional information about the request, such as content type, encoding, and authentication credentials.
  • Request body: The body of the PUT request contains the data to be updated on the server, which can be in a variety of formats such as JSON, XML, or form data. The format of the data should be specified in the Content-Type header.

Here is an example of the basic structure of a PUT request:

Java




PUT /api/users/1234 HTTP/1.1
Host: example.com
Content-Type: application/json
  
{
  "name": "Rahul Chauhan",
  "email": "rahulchauhan@gmail.com",
  "password": "password@123"
}


In this example, the PUT request is being sent to the /api/users/1234 endpoint on the example.com server, which indicates that the user with the ID of 1234 should be updated. The content type of the request body is specified as application/json, and the body contains a JSON object with the updated user’s name, email, and password.

It’s worth noting that the PUT method is idempotent, meaning that calling the same PUT request multiple times will result in the same resource state on the server. The entire resource is updated with the new data in the request body, which means that any fields not included in the request body will be overwritten with null or default values.

PATCH

The PATCH method is used to partially update a resource. It is useful when you want to update only a few fields of a resource without replacing the entire resource. In a PATCH request, you specify the fields that need to be updated in the request body.

Example: To update only the email address of a user with id 123, a PATCH request can be sent to the /users/123 endpoints with the updated email address in the request body.

The structure of a PATCH request in HTTP typically includes the following elements:

  • Request line: The first line of the request contains the HTTP method (PATCH), the resource path, and the HTTP version.
  • Headers: Headers provide additional information about the request, such as content type, encoding, and authentication credentials.
  • Request body: The body of the PATCH request contains a set of instructions on how to modify the resource on the server. The instructions can be in a variety of formats such as JSON, XML, or plain text, and should be specified in the Content-Type header.

Here is an example of the basic structure of a PATCH request:

Java




PATCH /api/users/1234 HTTP/1.1
Host: example.com
Content-Type: application/json-patch+json
  
[
  { "op": "replace", "path": "/name", "value": "Rahul Chauhan" },
  { "op": "add", "path": "/address", "value": "123 Main St." },
  { "op": "remove", "path": "/password" }
]


In the above example, the PATCH request is being sent to the /api/users/1234 endpoint on the example.com server, which indicates that the user with the ID of 1234 should be modified. The content type of the request body is specified as application/json-patch+json, which indicates that the body contains a set of JSON Patch instructions. The JSON Patch format is a standard for describing changes to a JSON document.

The instructions in the request body specify that the user’s name should be replaced with “Rahul Chauhan”, a new “address” field should be added with the value “123 Main St.”, and the “password” field should be removed from the user object.

It’s worth noting that the PATCH method is not idempotent, meaning that calling the same PATCH request multiple times may result in different resource states on the server. The PATCH method is typically used for making partial updates to a resource, rather than completely replacing it as with the PUT method.

Java code that demonstrates how to use these HTTP methods in a RESTful API.Assuming we have a simple User resource with the following properties: id, name, and email. Here’s an example implementation of a UserController class using the Spring Boot framework:

Java




@RestController
@RequestMapping("/users")
public class UserController {
  
    @Autowired
    private UserService userService;
  
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User createdUser = userService.createUser(user);
        return ResponseEntity.created(URI.create("/users/" + createdUser.getId())).body(createdUser);
    }
  
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        User updatedUser = userService.updateUser(id, user);
        return ResponseEntity.ok(updatedUser);
    }
  
    @PatchMapping("/{id}")
    public ResponseEntity<User> updateUserEmail(@PathVariable Long id, @RequestBody String email) {
        User updatedUser = userService.updateUserEmail(id, email);
        return ResponseEntity.ok(updatedUser);
    }
  
}


In the above example, we have implemented three methods for the CRUD operations on User resources. The createUser method uses the HTTP POST method to create a new user resource. The updateUser method uses the HTTP PUT method to update an entire User resource. Finally, the updateUserEmail method uses the HTTP PATCH method to update only the email address of a User resource.

Note: Note that in the example above, we used Spring Boot’s @PostMapping, @PutMapping, and @PatchMapping annotations to map the HTTP requests to the appropriate method.

Below are some best practices to help you choose the right HTTP method for your RESTful API operations:

  1. Use POST for creating a new resource, PUT for updating an entire resource, and PATCH for updating a portion of a resource.
  2. Use POST for operations that are not CRUD, such as triggering an action on the server.
  3. Use PUT only when you have the entire representation of the resource, including fields that are not being updated.
  4. Use PATCH when you only need to update a portion of the resource.
  5. Always provide appropriate response codes (e.g., 201 for a successful POST, 200 for a successful PUT or PATCH).
  6. Ensure that the resource identifier (URI) is consistent across all operations.
  7. Consider the idempotency of the HTTP method. Idempotent methods can be called repeatedly without changing the outcome. For example, a GET request is idempotent since it always returns the same response for the same resource. On the other hand, a POST request is not idempotent since it creates a new resource every time it is called.
  8. Consider the safety of the HTTP method. Safe methods do not modify the resource on the server. GET and HEAD requests are safe methods, while PUT, POST, DELETE, and PATCH requests are not.
  9. Consider the complexity of the resource being updated. If the resource is simple, it may be easier to use PUT to update the entire resource. However, if the resource is complex, PATCH may be a better option since it allows you to update specific fields without overwriting the entire resource.
  10. Consider the API’s compatibility with existing HTTP implementations. Some HTTP clients or servers may not support certain HTTP methods or may have restrictions on their use. For example, some firewalls may block HTTP methods other than GET and POST.
  11. Consider the security implications of the HTTP method. Some HTTP methods may be more secure than others. For example, a GET request with sensitive information in the query string may be logged in server logs, whereas a POST request with sensitive information in the request body may be encrypted.
  12. By taking these additional considerations into account, you can choose the appropriate HTTP method for your RESTful API operations based on the requirements of your application and the needs of your users.

By following these best practices, you can ensure that your RESTful API is scalable, easy to use, and consistent across all operations. Below are some additional key features and considerations for the PUT, POST, and PATCH HTTP methods:

Difference Between PUT, POST, and PATCH

PUT

  • The PUT method is idempotent, meaning that calling the same request multiple times will result in the same resource state on the server.
  • The entire resource is updated with the new data in the request body, which means that any fields not included in the request body will be overwritten with null or default values.
  • PUT is often used to create a new resource when the client specifies the resource identifier. For example, when creating a new user with a specific ID.
  • If the resource specified in the request line does not exist, the server may create a new resource or return an error, depending on the API design.

POST

  • The POST method is not idempotent, meaning that calling the same request multiple times may result in different resource states on the server.
  • POST is often used to create a new resource when the client does not specify the resource identifier. For example, when creating a new user and the server generates a new ID.
  • The request body of a POST request can be in a variety of formats, including form data, JSON, XML, or plain text.
  • The server may choose to return a new resource identifier in the response body, which can be useful for further interactions with the resource.

PATCH

  • The PATCH method is not idempotent, meaning that calling the same request multiple times may result in different resource states on the server.
  • PATCH is often used to make partial updates to a resource, rather than completely replacing it as with the PUT method.
  • The request body of a PATCH request typically contains a set of instructions on how to modify the resource on the server, such as the JSON Patch format.
  • Care should be taken when designing PATCH requests to ensure that they do not cause unintended side effects or conflicts with other concurrent requests modifying the same resource.

Conclusion

In conclusion, the choice of HTTP method (PUT, POST, PATCH) for RESTful API operations depends on the specific requirements and semantics of the API.

PUT is suitable when the entire resource needs to be updated and the client specifies the resource identifier. POST is suitable when creating a new resource and the client does not specify the resource identifier. PATCH is suitable when making partial updates to a resource.

It is important to consider the idempotency of the HTTP method, the request and response formats, and the potential side effects and conflicts of the operation. By choosing the appropriate HTTP method and designing the API carefully, you can ensure that your API is efficient, reliable, and easy to use.



Last Updated : 14 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads