JAVASCRIPT

Making a PATCH Request to Update a Partial Resource

Learn to send a `PATCH` request using JavaScript's `fetch` API for efficient partial updates to resources, sending only changed fields to the server.

const userId = '123'; // ID of the resource to update
const updates = {
  email: '[email protected]',
  status: 'active' // Only sending fields that need updating
};

fetch(`https://api.example.com/users/${userId}`, {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_AUTH_TOKEN' // If authentication is required
  },
  body: JSON.stringify(updates)
})
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return response.json();
})
.then(updatedUser => console.log('User updated successfully:', updatedUser))
.catch(error => console.error('Error updating user:', error));
How it works: The `PATCH` HTTP method is used to apply partial modifications to a resource. Unlike `PUT`, which typically replaces an entire resource, `PATCH` allows you to send only the fields that need to be changed, making updates more efficient and reducing unnecessary data transfer. This snippet shows how to construct a `PATCH` request with a JSON payload using the `fetch` API, targeting a specific resource by its ID, and including an optional authorization token.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs