Activity 29: HTTP Methods
Here’s an overview of the main HTTP methods commonly used in RESTful APIs, along with examples and guidance on when to use each:
1. GET
Purpose: The
GETmethod retrieves data from a server without altering its state. This method is idempotent, meaning repeated requests yield the same result.Example: Accessing a list of users from
http://api.example.com/userswill return a JSON array of user objects. For a specific user, a request tohttp://api.example.com/users/123will retrieve that user's details.Use Cases: Use
GETfor read-only actions, such as displaying data on a webpage, searching, or fetching user details.
// Retrieve all users
fetch('https://api.example.com/users', {
method: 'GET',
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Retrieve a specific user by ID
fetch('https://api.example.com/users/123', {
method: 'GET',
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
2. POST
Purpose:
POSTis used to send data to a server to create a new resource. UnlikeGET, this method can change the server's state and is not idempotent—meaning, each call could produce a unique result.Example: To create a new user, a
POSTrequest tohttp://api.example.com/userswith JSON data, such as{ "name": "Jane Doe", "email": "jane@example.com" }, will add a new user to the database.Use Cases: Use
POSTfor actions where data needs to be created, such as user sign-ups, posting a new blog, or submitting a form.
// Data for the new user
const newUser = {
name: 'Jane Doe',
email: 'jane@example.com'
};
// Create a new user
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log('User created:', data))
.catch(error => console.error('Error:', error));
3. PUT
Purpose: The
PUTmethod updates an existing resource or creates one if it does not exist. This method is idempotent, as repeated identical requests have the same effect as one request.Example: To update a user’s email, you might send a
PUTrequest tohttp://api.example.com/users/123with the complete updated user object in JSON format, such as{ "id": 123, "name": "Jane Doe", "email": "newemail@example.com" }.Use Cases:
PUTis best for updates that replace entire objects or resources, such as editing user details or replacing configurations.
// Updated data for the user
const updatedUser = {
id: 123,
name: 'Jane Smith',
email: 'jane.smith@example.com'
};
// Update user with ID 123
fetch('https://api.example.com/users/123', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updatedUser)
})
.then(response => response.json())
.then(data => console.log('User updated:', data))
.catch(error => console.error('Error:', error));
4. DELETE
Purpose:
DELETEremoves a specified resource from the server. This method is also idempotent; deleting the same resource multiple times results in the same outcome—removal of that resource.Example: A
DELETErequest tohttp://api.example.com/users/123will remove the user with ID 123.Use Cases: Use
DELETEwhen resources should be permanently removed, such as deleting a post, a user account, or clearing old records.
// Delete user with ID 123
fetch('https://api.example.com/users/123', {
method: 'DELETE'
})
.then(response => {
if (response.ok) {
console.log('User deleted successfully');
} else {
console.error('Error deleting user');
}
})
.catch(error => console.error('Error:', error));
5. PATCH
Purpose:
PATCHallows for partial updates of a resource. UnlikePUT, which updates the entire resource,PATCHmodifies only specified fields.Example: To update only the email of a user, send a
PATCHrequest tohttp://api.example.com/users/123with the JSON{ "email": "updatedemail@example.com" }.Use Cases:
PATCHis ideal for cases where you need to modify parts of a resource, such as updating a user’s profile picture or changing a single field without affecting other data.
// Partial update for the user
const partialUpdate = {
email: 'updated.email@example.com'
};
// Partially update user with ID 123
fetch('https://api.example.com/users/123', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(partialUpdate)
})
.then(response => response.json())
.then(data => console.log('User partially updated:', data))
.catch(error => console.error('Error:', error));
