Handling Different HTTP Methods: PUT, PATCH, DELETE
You'll learn how to use fetch() with PUT, PATCH, and DELETE methods to update and remove resources on a server.
Beyond GET and POST
You've already used GET (retrieve data) and POST (create data). Now you need the other key HTTP methods:
- PUT: Replace an entire resource
- PATCH: Update part of a resource
- DELETE: Remove a resource
Think of it like editing a document: PUT rewrites the whole file, PATCH changes specific paragraphs, and DELETE throws it in the trash.
Using PUT to Replace a Resource
fetch('https://api.example.com/users/42', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Alice Updated',
email: 'alice@example.com',
age: 30
})
})
.then(response => response.json())
.then(data => console.log('Updated:', data));
PUT typically sends the complete updated resource.
Using PATCH for Partial Updates
fetch('https://api.example.com/users/42', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
age: 31 // Only update age
})
})
.then(response => response.json())
.then(data => console.log('Patched:', data));
PATCH sends only the fields you want to change.
Using DELETE to Remove Resources
fetch('https://api.example.com/users/42', {
method: 'DELETE'
})
.then(response => {
if (response.ok) {
console.log('Deleted successfully');
}
});
DELETE often returns an empty response or status confirmation.
Key Takeaway: Use method: 'PUT' for full replacements, method: 'PATCH' for partial updates, and method: 'DELETE' for removals—the pattern is identical to POST, just changing the method name.