0
0
Rest APIprogramming~5 mins

PATCH for partial updates in Rest API

Choose your learning style9 modes available
Introduction

PATCH lets you change only some parts of data without sending everything again. It saves time and data.

You want to update just the email address of a user without changing other details.
You need to fix a typo in a product description without resending the whole product info.
You want to mark a task as done without changing its title or deadline.
You want to update the status of an order without resending customer info.
Syntax
Rest API
PATCH /resource/{id}
{
  "field_to_update": "new_value"
}

PATCH requests include only the fields you want to change.

The server updates those fields and keeps the rest unchanged.

Examples
Update only the email of user with ID 123.
Rest API
PATCH /users/123
{
  "email": "newemail@example.com"
}
Mark task 456 as completed without changing other details.
Rest API
PATCH /tasks/456
{
  "completed": true
}
Sample Program

This Python code sends a PATCH request to update only the phone number of user 123. It prints success or failure and shows updated data.

Rest API
import requests

url = 'https://api.example.com/users/123'

# Data to update only the phone number
patch_data = {
    "phone": "+1234567890"
}

response = requests.patch(url, json=patch_data)

if response.status_code == 200:
    print('Update successful')
    print('Updated user data:', response.json())
else:
    print('Update failed with status:', response.status_code)
OutputSuccess
Important Notes

PATCH is different from PUT, which replaces the whole resource.

Always send only the fields you want to change with PATCH.

Some servers may not support PATCH; check API docs.

Summary

PATCH updates parts of data without sending everything.

Use PATCH to save bandwidth and time when changing small details.

Send only the fields you want to update in the PATCH request body.