PATCH Method
How to make PATCH requests with speedcast-api
🔧 Using PATCH Method
PATCH requests update only specific fields of a resource, preserving other existing data. Perfect for partial updates when you don't need to replace the entire resource.
Basic Usage
1. Import and Create API Client
import { SpeedcastApi } from 'speedcast-api';
// Create an API client
const api = new SpeedcastApi({
baseURL: 'https://api.example.com'
});
2. Simple PATCH Request
// Partially update a user's profile
const updateData = {
email: "newemail@example.com",
};
const response = await api.patch('/users/123', updateData);
// Process the successful response
console.log(`Status: ${response.status}`); // e.g., 200 OK
console.log('Updated user:', response.data);
Advanced Usage
With Type Safety
// Define interfaces for update request and response
interface UserUpdateRequest {
email?: string;
name?: string;
}
interface UserUpdateResponse {
id: number;
email: string;
updatedAt: string;
}
const updateData: UserUpdateRequest = {
email: "john.doe@example.com",
name: "John Doe",
};
const response = await api.patch<UserUpdateResponse>('/users/123', updateData);
// TypeScript knows the exact shape of the response
const updatedUser = response.data;
console.log(updatedUser.updatedAt);
Custom Options
Add Headers
const response = await api.patch('/users/123', updateData, {
headers: {
'X-Update-Source': 'ProfileSettings',
'Authorization': `Bearer ${yourAuthToken}`,
},
});
Set Timeout
const response = await api.patch('/users/123', updateData, {
timeout: 12000, // 12 seconds
});
Configure Retries
const response = await api.patch('/users/123', updateData, {
retries: 2, // Retry twice if needed
});
Error Handling
try {
const response = await api.patch('/users/123', updateData);
console.log('Update successful');
} catch (error) {
console.error('Update failed:', error);
}
Full Example Scenario
import { SpeedcastApi } from 'speedcast-api';
const api = new SpeedcastApi({
baseURL: 'https://api.example.com',
defaultHeaders: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout: 8000,
retries: 2
});
async function updateUserProfile() {
try {
// Partial update of user profile
const profileUpdates = {
preferences: {
theme: "dark",
notifications: true,
},
contactInfo: {
phone: "+1234567890",
},
};
const response = await api.patch<UserProfile>('/profile', profileUpdates, {
headers: {
'Authorization': `Bearer ${yourAuthToken}`,
}
});
// Update local state with new profile data
updateLocalProfile(response.data);
console.log('Profile updated successfully');
return response.data;
} catch (error) {
console.error('Failed to update profile:', error);
throw error;
} finally {
// Clean up operations
clearFormChanges();
}
}
Practical Use Cases
Partial Updates
// Update only specific fields
const partialUpdate = {
// Only update these specific fields
status: "active",
lastLogin: new Date().toISOString(),
};
const response = await api.patch('/users/current', partialUpdate);
Complex Nested Updates
// Update nested object properties
const nestedUpdate = {
settings: {
preferences: {
language: "en",
timezone: "UTC",
},
},
};
const response = await api.patch('/account', nestedUpdate);
PATCH vs PUT Comparison
P
PATCH: Update specific fields
// Only specified fields are updated
api.patch('/users/123', { email: "new@example.com" });
// Other user data remains unchanged
P
PUT: Replace entire resource
// All fields must be included, as the whole resource is replaced
api.put('/users/123', {
name: "John",
email: "john@example.com",
age: 30,
role: "user"
});
Response Structure
The response from a PATCH request has the following structure:
interface ApiResponse<T = any> {
data: T; // Response data
status: number; // HTTP status code
statusText: string; // HTTP status text
headers: Record<string, string>; // Response headers
}
💡 Quick Tips
- Use PATCH for partial updates (unlike PUT which replaces entire resource)
- Only include the fields you want to modify
- Define explicit TypeScript interfaces for both request and response
- Check the API documentation to understand how nested updates are handled
- Some APIs might implement PATCH differently - check their specific requirements