Skip to Content

What is difference between put and PATCH in REST API?


PUT and PATCH are two HTTP methods used for updating resources in a REST API. The main difference between them is that PUT replaces the entire resource with a new representation, while PATCH only updates part of the resource.

PUT and PATCH both allow making changes to an existing resource, but the semantics of the operations are different. With PUT, the client sends a complete representation of the resource to replace the existing one. Whereas with PATCH, the client only sends a set of instructions to modify the resource.

Some key differences between PUT and PATCH:

Idempotence

PUT is idempotent, meaning calling it multiple times with the same parameters should not change the outcome. PATCH is not inherently idempotent, subsequent identical requests may continue updating the same fields and have side effects. However, we can design PATCH requests to be idempotent, like only updating a field if the value is different from the previous request.

Request body

PUT requires the entire resource representation to be sent in the request body. PATCH requires a set of instructions specifying the changes, like a JSON patch document.

Behavior

PUT replaces the target resource completely. PATCH only updates the specified attributes of the resource.

Response

The common response to a PUT request is 200 OK with the updated resource in the body. PATCH commonly returns a 200 OK without any body content.

Some other aspects and usage considerations for each method:

PUT Method

Complete replacement

With PUT, the client sends the entire updated representation of the resource in the request body. The resource on the server is then replaced with the representation in the request body.

This amounts to replacing the entire resource wholesale rather than just updating parts of it.

Idempotence

PUT is defined to be idempotent by the HTTP specification. That means multiple identical PUT requests should have the same effect as a single request.

So sending the same PUT request multiple times will just overwrite the resource with same new state every time. The end result will be identical to calling it once.

This idempotence makes PUT operations very predictable.

Update full resource

PUT requires the client to have access to the full resource representation to update the resource. This is feasible if the client itself generated the original representation or requested it earlier.

But if the client only knows about a subset of properties that need to be modified, using PUT becomes difficult since it involves sending the full resource representation.

Unknown properties

When updating a resource using PUT, the client has to send values for all editable properties of the resource in the request. If any property is missed, it could be reset to default or null value after the update.

So PUT requires the client to know the full resource schema beforehand to avoid unintended changes.

Use cases

PUT is most useful when:

– The client has access to the full resource representation to replace. For example, an API client that generates new representations locally before updating resources.

– Full resource state is known beforehand and needs to be replaced conclusively. For example, update operations that involve replacement of complex structured data like documents or configuration files.

– Idempotence is required since the same request can be sent multiple times.

PATCH Method

Partial update

PATCH allows making partial updates to a resource. The client only sends the changes that need to be applied, not the whole representation.

The server applies these incremental changes to the resource without replacing the entire resource like PUT.

Not inherently idempotent

The PATCH method itself does not specify idempotence like PUT. The same PATCH request applied multiple times may produce different results if it is designed to incrementally update fields.

However, we can make PATCH requests idempotent by being careful about the operation semantics. Like only updating a value if it is different from the previous value.

Update specific fields

The request body in PATCH contains instructions about what fields should be updated, added or removed. This works well when only specific parts of the resource need to be modified.

The client does not need to send full resource representation.

Express partial modifications

PATCH allows fine-grained control over what data is being modified in the resource. The update instructions can specify that only certain fields or subset of elements in an array should be updated.

This works better than PUT when the exact shape of the update is known in advance and needs to be restricted to certain parts of the resource.

Use cases

PATCH is useful in cases like:

– The client only knows the specific fields that need to be updated, not the full resource state. For example, updating only the status field of an order resource.

– Very large resources where sending the full updated representation is inefficient. Only the modified parts can be sent.

– Updates need to be restricted to certain fields or properties based on application logic. The full resource update semantics of PUT is not required.

– Individual incremental updates need to be logged and rolled back if required. With PUT, intermediary updates are replaced entirely.

Guidelines for choosing between PUT vs PATCH

Here are some guidelines on when to choose one method over the other:

Use PUT when

– You need full replacement semantics rather than partial updates.

– You are exposing mutable resources that clients can update by replacing wholesale.

– Client has full access to updated resource representation.

– Idempotence is required.

Use PATCH when

– You need to update only parts of a resource selectively.

– Client only knows a subset of properties to modify.

– Resource is large and inefficient for full replacement.

– Individual incremental updates need to be tracked.

– Updates to certain fields need access control.

Use cases comparison

Use case PUT appropriate PATCH appropriate
Update status field of order No Yes
Update address fields of user profile No Yes
Change document title No Yes
Overwrite entire settings config file Yes No
Replace user profile resource entirely Yes No
Upload new version of file Yes No

PUT vs PATCH request examples

Let’s look at some examples of PUT and PATCH requests for updating a user resource.

PUT request

Here is how we could replace the entire user resource using a PUT request:

“`
PUT /users/1234
Content-Type: application/json

{
“id”: 1234,
“name”: “John Doe”,
“email”: “[email protected]”,
“address”: {
“line1”: “123 Main St”,
“city”: “Anytown”,
“state”: “CA”,
“zip”: “12345”
}
}
“`

This PUT request replaces user 1234 with the JSON representation in the body wholesale.

PATCH request

To update just the email field of the user with PATCH, we can do:

“`
PATCH /users/1234
Content-Type: application/json-patch+json

[
{ “op”: “replace”,
“path”: “/email”,
“value”: “[email protected]
}
]
“`

This PATCH request only updates user 1234’s email, leaving other fields unchanged.

PATCH request 2

To update just the zip field of the user’s address, the PATCH request would be:

“`
PATCH /users/1234
Content-Type: application/json-patch+json

[
{ “op”: “replace”,
“path”: “/address/zip”,
“value”: “54321”
}
]
“`

This only modifies the specific address zip field leaving everything else unchanged.

Hypermedia – The REST way

Simply choosing PUT or PATCH is not enough to make an API RESTful. A truly RESTful API should follow the principle of hypermedia as the engine of application state (HATEOAS).

This means the API responses should contain links to transition to appropriate application states. The client just needs to follow the links, instead of hardcoded URLs, to interact with the API.

For example, a GET response can include PUT and PATCH links within to update the returned resource:

“`
GET /users/1234

{

“id”: 1234,
“name”: “John Doe”,
“links”: [
{
“rel”: “edit”,
“type”: “full”,
“method”: “PUT”,
“href”: “/users/1234”
},
{
“rel”: “edit”,
“type”: “partial”,
“method”: “PATCH”,
“href”: “/users/1234”
}
]

}
“`

This allows the client to dynamically discover available state transitions like updating the user resource.

Other aspects like HTTP method, request format etc. can be conveyed through link relations and link types instead of out-of-band documentation.

JSON:API – Standard JSON format

For REST APIs that communicate in JSON, the JSON:API specification defines standard JSON payload formatting conventions.

It provides a common format for exchanging resource representations while keeping API interface generic.

Some of the key aspects it standardizes:

– JSON objects must contain a “data” property for primary data
– Resources are identified by a “type” and “id”
– Links use a “relationships” object
– Metadata like pagination is standardized
– Errors are consistently formatted

Example JSON:API document:

“`
{
“data”: {
“type”: “users”,
“id”: “1234”,
“attributes”: {

},
“relationships”: {

}
},
“links”: {

}
}
“`

Using standardized formats improves interoperability across API clients and implementations.

Versioning REST APIs

REST itself does not define any formal versioning scheme. But APIs still need to evolve without breaking existing clients.

Some common approaches used in practice are:

**URI versioning**

– Append version number to URI paths e.g. `/v1/users`, `/v2/users`
– Clean and simple
– Existing URIs keep working

**Custom request header**

– Send API version in custom header like `Api-Version: 1.2.3`
– Does not change URIs
– Header can be easily passed by proxies etc.

**Request parameter**

– Send as query parameter e.g. `/users?api_version=1.2.3`
– Works with standard cache control
– Avoids new custom headers

**Media type versioning**

– Use version specific media type like `application/vnd.myapp.v1+json`
– Supported by content negotiation
– Changes request and response formats

**Proper hypermedia**

– Use hypermedia links to negotiate API versions
– Allows dynamic discovery of API evolution
– Changes hypermedia format, not resource URIs

Deciding factors are compatibility, performance, caching, discovery, flexibility etc.

Conclusion

PUT and PATCH allow mutating resources in a REST API but have different semantics.

PUT replaces the entire resource state. PATCH applies partial modifications.

Key factors when deciding between them are idempotence requirements, knowledge of full vs partial resource state, size of resources and how granular the updates need to be.

Following REST principles like HATEOAS help build truly RESTful APIs. Standard JSON formats like JSON:API improve interoperability.

Overall, PUT and PATCH provide different but complementary functionality for updating resources in REST APIs.