What is the Difference Between PUT, POST, and PATCH in RESTful API?
Last Updated :
14 May, 2023
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:
- Use POST for creating a new resource, PUT for updating an entire resource, and PATCH for updating a portion of a resource.
- Use POST for operations that are not CRUD, such as triggering an action on the server.
- Use PUT only when you have the entire representation of the resource, including fields that are not being updated.
- Use PATCH when you only need to update a portion of the resource.
- Always provide appropriate response codes (e.g., 201 for a successful POST, 200 for a successful PUT or PATCH).
- Ensure that the resource identifier (URI) is consistent across all operations.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
Similar Reads
How to set height equal to dynamic width (CSS fluid layout) ?
To create a fluid layout in CSS, set an element's height to the same value as its dynamic width. This makes the layout more adaptable and responsive since the element's height will automatically change depending on the viewport's width. It is possible to determine the element's height by using the p
2 min read
How to Set Height Equal to Dynamic Width (CSS fluid layout) in JavaScript ?
A key component of constructing a contemporary website in web development is developing an adaptable and dynamic layout. Setting the height of an element equal to its dynamic width, often known as a CSS fluid layout, is a common difficulty in accomplishing this. When the screen size changes and you
4 min read
How to Create Equal Height Columns in CSS ?
Equal Height Columns in CSS refer to ensuring that multiple columns in a layout have the same height, regardless of the content inside each column. This can be achieved using modern CSS techniques like Flexbox, CSS Grid, or the Table display property. Table of Content Using FlexUsing GridUsing Table
3 min read
How to make div height expand with its content using CSS ?
When designing a webpage, ensuring that a div adjusts its height according to its content is important for creating a flexible and responsive layout. By using CSS, you can easily make a div adapt to varying content sizes, which is particularly useful when dealing with dynamic or unpredictable conten
3 min read
How to Set Viewport Height & Width in CSS ?
Set viewport height and width in CSS is essential for creating responsive and visually appealing web designs. We'll explore the concepts of setting viewport height and width by using various methods like CSS Units, Viewport-Relative Units, and keyframe Media Queries. Table of Content Setting viewpor
3 min read
How to Stretch Elements to Fit the Whole Height of the Browser Window Using CSS?
To stretch elements to fit the whole height of the browser window using CSS, you can use "vh" units, where "1vh" equals 1% of the viewport height, so setting the height to "100vh" spans the entire height. Approach: Using CSS height PropertyIn this approach, we are using the Height property to fit th
1 min read
How to get the height of device screen in JavaScript ?
Given an HTML document which is running on a device. The task is to find the height of the working screen device using JavaScript. Prerequisite - How to get the width of device screen in JavaScript ? Example 1: This example uses window.innerHeight property to get the height of the device screen. The
2 min read
How to fit text container width dynamically according to screen size using CSS ?
In this article, we have given a text paragraph and the task is to fit the text width dynamically according to screen size using HTML and CSS. Some of the important properties used in the code are as follows- display-grid: It helps us to display the content on the page in the grid structure.grid-gap
7 min read
How to Adjust the Width and Height of an iframe to Fit the Content Inside It?
When using the <iframe> tag in HTML, the content inside the iframe is displayed with a default size if the width and height attributes are not specified. Even if the dimensions are specified, it can still be difficult to perfectly match the iframe’s size with the content inside it. This can be
4 min read
jQWidgets jqxLayout height Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxLayout is used for representing a jQuery widget that is used for the creation of complex layouts with nested
2 min read
How to Make Flexbox Items of Same Size Using CSS?
To make Flexbox items the same size using CSS, you can use various properties to control the dimensions of the items and ensure consistency in layout. By default, Flexbox items can have different sizes based on their content, but with a few CSS changes, you can make them uniform. 1. Using Flex Prope
5 min read
How to Specify Height to Fit-Content with Tailwind CSS ?
Specifying height to fit-content in Tailwind CSS means setting an element’s height to automatically adjust based on its content. Tailwind provides the h-fit utility class, which ensures the element's height dynamically adapts to its content's size. Adjusting Height with h-fit in Tailwind CSSThis app
2 min read
How to detect the change in DIV's dimension ?
The change in a div's dimension can be detected using 2 approaches: Method 1: Checking for changes using the ResizeObserver Interface The ResizeObserver Interface is used to report changes in dimensions of an element. The element to be tracked is first selected using jQuery. A ResizeObserver object
4 min read
How to Change the Height and Width of an Element with JavaScript?
To change the height and width of an element using JavaScript, you can directly manipulate the style property of the element. Here’s a simple guide on how to do it: Example:[GFGTABS] HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <m
1 min read
Primer CSS Layout width and height
Primer CSS is a free open-source CSS framework that is built with the GitHub design system to provide support to the broad spectrum of Github websites. It creates the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are ste
5 min read
How to Create Equal Width Table Cell Using CSS ?
Creating equal-width table cells using CSS refers to adjusting the table's layout so that all columns maintain the same width. This technique ensures a consistent and organized appearance, making the table content easier to read and visually balanced. Here we are following some common approaches: Ta
3 min read
How to Set Width and Height of Span Element using CSS ?
The <span> tag is used to apply styles or scripting to a specific part of text within a larger block of content. The <span> tag is an inline element, you may encounter scenarios where setting its width and height becomes necessary. This article explores various approaches to set the widt
2 min read
How to Set 100% Height with Padding/Margin in CSS ?
In this article, we'll explore CSS layouts with 100% width/height while accommodating padding and margins. In the process of web page design, it is often faced with scenarios where the intention is to have an element fill the entire width and/or height of its parent container, while also maintaining
3 min read
How to give a div tag 100% height of the browser window using CSS
CSS allows to adjustment of the height of an element using the height property. While there are several units to specify the height of an element. Set the height of a <div> to 100% of its parent container with height: 100%, or use height: 100vh; for a full viewport height, ensuring the <div
2 min read