How to Make an HTTP PATCH Request Using Axios
This guide explains how to correctly perform an HTTP PATCH request
using the Axios library in JavaScript. You will learn the standard
syntax for partial data updates, how to send custom request headers, how
to handle responses with modern async/await syntax, and how
to effectively catch and manage network or server errors.
Understanding HTTP PATCH
An HTTP PATCH request applies partial modifications to an existing resource. Unlike an HTTP PUT request, which replaces an entire resource with the provided payload, PATCH only sends the specific fields that need to be updated.
Basic Syntax:
axios.patch()
Axios provides a dedicated shortcut method for PATCH requests:
axios.patch(url[, data[, config]])url: The endpoint where the target resource is located.data(optional): The JavaScript object or string containing the fields to update.config(optional): Configuration options such as headers, query parameters, or timeouts.
Example: Making a Basic PATCH Request
Using modern async/await syntax is the standard and
cleanest way to send a PATCH request:
const axios = require('axios');
async function updateUserDetails(userId, partialData) {
try {
const response = await axios.patch(
`https://api.example.com/users/${userId}`,
partialData
);
console.log('Status Code:', response.status);
console.log('Updated Data:', response.data);
return response.data;
} catch (error) {
if (error.response) {
// Server responded with a status code outside 2xx
console.error('Server Error:', error.response.status, error.response.data);
} else if (error.request) {
// Request was made but no response was received
console.error('Network Error: No response received', error.request);
} else {
// Error setting up the request
console.error('Error:', error.message);
}
}
}
// Usage Example
updateUserDetails(123, { email: 'newemail@example.com' });Passing Custom Headers and Authentication
To include authorization tokens or custom headers, pass a configuration object as the third argument:
const config = {
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
};
const updatePayload = {
status: 'active'
};
const response = await axios.patch(
'https://api.example.com/users/123',
updatePayload,
config
);Alternative: Using the Request Config Object
You can also execute a PATCH request by passing a comprehensive
configuration object to the main axios function:
const response = await axios({
method: 'patch',
url: 'https://api.example.com/users/123',
data: {
role: 'editor'
},
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
});