Mastering API HTTP Methods in JavaScript with fetch
http-methods-overview.png: "Chart explaining GET, POST, PUT, PATCH, and DELETE methods in JavaScript fetch API
In JavaScript, interacting with APIs involves using HTTP methods to perform operations like retrieving, sending, updating, or deleting data. These methods define the type of action you want to take on the server.
Commonly used with the fetch()
API, each HTTP method serves a specific purpose in RESTful API architecture.
Used to retrieve data from a server.
fetch('https://api.example.com/items')
.then(response => response.json())
.then(data => console.log(data));
Used to send new data to the server.
fetch('https://api.example.com/items', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'New Item' })
})
.then(response => response.json())
.then(data => console.log(data));
Used to update existing data on the server.
fetch('https://api.example.com/items/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Updated Item' })
})
.then(response => response.json())
.then(data => console.log(data));
Used to partially update a resource.
fetch('https://api.example.com/items/1', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ status: 'active' })
})
.then(response => response.json())
.then(data => console.log(data));
Used to remove a resource.
fetch('https://api.example.com/items/1', {
method: 'DELETE'
})
.then(response => {
if (response.ok) console.log("Deleted successfully");
});
Use headers for authentication, content types, and custom settings:
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
}
GET: Fetching user profile or list of products
POST: Registering a user or submitting a contact form
PUT: Updating full profile settings
PATCH: Changing a user's status or password
DELETE: Removing a product or account
Understanding HTTP methods is essential for working with web APIs. Each method represents a specific operation in the CRUD model (Create, Read, Update, Delete). Mastering them allows you to build dynamic, data-driven JavaScript applications.