Skip to main content

Command Palette

Search for a command to run...

Activity 29: HTTP Methods

Published
3 min readView as Markdown

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 GET method 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/users will return a JSON array of user objects. For a specific user, a request to http://api.example.com/users/123 will retrieve that user's details.

  • Use Cases: Use GET for 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: POST is used to send data to a server to create a new resource. Unlike GET, 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 POST request to http://api.example.com/users with JSON data, such as { "name": "Jane Doe", "email": "jane@example.com" }, will add a new user to the database.

  • Use Cases: Use POST for 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 PUT method 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 PUT request to http://api.example.com/users/123 with the complete updated user object in JSON format, such as { "id": 123, "name": "Jane Doe", "email": "newemail@example.com" }.

  • Use Cases: PUT is 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: DELETE removes 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 DELETE request to http://api.example.com/users/123 will remove the user with ID 123.

  • Use Cases: Use DELETE when 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: PATCH allows for partial updates of a resource. Unlike PUT, which updates the entire resource, PATCH modifies only specified fields.

  • Example: To update only the email of a user, send a PATCH request to http://api.example.com/users/123 with the JSON { "email": "updatedemail@example.com" }.

  • Use Cases: PATCH is 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));