Mastering API HTTP Methods in JavaScript with fetch

6/29/2025
All Articles

http-methods-overview.png: "Chart explaining GET, POST, PUT, PATCH, and DELETE methods in JavaScript fetch API

Mastering API HTTP Methods in JavaScript with fetch

API HTTP Methods in JavaScript

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.


🔹 Common HTTP Methods

1. GET

Used to retrieve data from a server.

fetch('https://api.example.com/items')
  .then(response => response.json())
  .then(data => console.log(data));

2. POST

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));

3. PUT

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));

4. PATCH

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));

5. DELETE

Used to remove a resource.

fetch('https://api.example.com/items/1', {
  method: 'DELETE'
})
.then(response => {
  if (response.ok) console.log("Deleted successfully");
});

Adding Headers

Use headers for authentication, content types, and custom settings:

headers: {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer your-token'
}


Real-World Use Cases

  • 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

Conclusion

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.

Article