Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

HTTP PUT and PATCH Methods

Introduction

The HTTP protocol defines a set of request methods that indicate the desired action to be performed for a given resource. Among these methods, PUT and PATCH are commonly used for updating resources. Understanding when and how to use these methods is essential for effective web API design.

Definitions

PUT Method

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 client sends the entire representation of the resource to be updated.

PATCH Method

The PATCH method is used to apply partial modifications to a resource. Unlike PUT, PATCH allows sending only the changes rather than the complete representation of the resource.

PUT Method

When using the PUT method, the request typically requires a payload that contains the full representation of the resource. The server processes this request and updates the resource accordingly.

Note: If the resource does not exist, the PUT method can create a new resource at the specified URI.

Example


PUT /users/123
Content-Type: application/json

{
    "name": "John Doe",
    "email": "john.doe@example.com"
}
                

PATCH Method

The PATCH method is more efficient for updates where only certain fields need to be changed. The request body should only include the fields that need modification.

Tip: Use PATCH for updates that do not require a complete resource representation.

Example


PATCH /users/123
Content-Type: application/json

{
    "email": "new.email@example.com"
}
                

Comparison of PUT and PATCH

Feature PUT PATCH
Update Type Full resource replacement Partial resource update
Request Body Requires the complete resource Requires only the fields to be updated
Idempotency Yes Yes

Best Practices

  1. Use PUT when the client needs to send the entire resource representation.
  2. Use PATCH when only specific fields need to be updated.
  3. Ensure idempotency; repeated requests should not change the state beyond the initial application.
  4. Validate input data on the server side to prevent issues with data integrity.

Frequently Asked Questions (FAQ)

Can I use PUT to create a resource?

Yes, if the resource does not already exist at the specified URI, PUT can create a new resource.

Is PATCH more efficient than PUT?

Yes, PATCH is generally more efficient for partial updates because it only sends the fields that need to be changed.

Are PUT and PATCH idempotent?

Both methods are idempotent, meaning that making the same request multiple times will produce the same result.