DEV Community

Dev Cookies
Dev Cookies

Posted on

πŸš€ Mastering the Fetch API in JavaScript β€” GET, POST, PUT, PATCH, DELETE (With Examples)

Making HTTP requests is a fundamental part of web development. Whether you're fetching data, submitting a form, updating content, or deleting a resource β€” the Fetch API makes it clean and modern.

In this blog, we'll walk through how to use the Fetch API to make GET, POST, PUT, PATCH, and DELETE requests β€” with real-world examples.


πŸ” What is the Fetch API?

The Fetch API provides a simple and native way to make HTTP requests in the browser. It returns Promises and works with async/await.

βœ… It’s built into all modern browsers β€” no need for extra libraries like Axios.


πŸ“¦ Basic Syntax

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Or using async/await:

const response = await fetch(url, options);
const data = await response.json();
Enter fullscreen mode Exit fullscreen mode

βœ… 1. GET Request (Fetch Data)

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching data:', error));
Enter fullscreen mode Exit fullscreen mode

βœ… With async/await

const fetchPosts = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
};

fetchPosts();
Enter fullscreen mode Exit fullscreen mode

πŸ“ 2. POST Request (Create Data)

const createPost = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: 'New Post',
        body: 'This is the body of the new post.',
        userId: 1
      })
    });

    const data = await response.json();
    console.log('Created Post:', data);
  } catch (error) {
    console.error('Error creating post:', error);
  }
};

createPost();
Enter fullscreen mode Exit fullscreen mode

πŸ”„ 3. PUT Request (Update Entire Resource)

const updatePost = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        id: 1,
        title: 'Updated Post',
        body: 'This post has been updated.',
        userId: 1,
      }),
    });

    const data = await response.json();
    console.log('Updated Post:', data);
  } catch (error) {
    console.error('Error updating post:', error);
  }
};

updatePost();
Enter fullscreen mode Exit fullscreen mode

🩹 4. PATCH Request (Partial Update)

const patchPost = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: 'Partially Updated Title',
      }),
    });

    const data = await response.json();
    console.log('Partially Updated Post:', data);
  } catch (error) {
    console.error('Error patching post:', error);
  }
};

patchPost();
Enter fullscreen mode Exit fullscreen mode

❌ 5. DELETE Request (Remove Data)

const deletePost = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
      method: 'DELETE',
    });

    if (response.ok) {
      console.log('Post deleted successfully.');
    } else {
      console.error('Failed to delete post. Status:', response.status);
    }
  } catch (error) {
    console.error('Error deleting post:', error);
  }
};

deletePost();
Enter fullscreen mode Exit fullscreen mode

🧠 Pro Tip: Handle HTTP Errors Manually

The Fetch API does not throw an error for HTTP error status codes (e.g., 404 or 500). You need to check response.ok yourself.

const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch failed:', error);
  }
};
Enter fullscreen mode Exit fullscreen mode

πŸ“‹ Summary Table

HTTP Method Description Example Use Case
GET Read data Fetch list of blog posts
POST Create new data Submit a new post
PUT Replace entire resource Update all fields of a post
PATCH Update part of resource Modify title or description
DELETE Remove data Delete a post by ID

βš”οΈ Fetch API vs Axios (Quick Glance)

Feature Fetch API Axios
Native Support βœ… ❌
Automatic JSON ❌ βœ…
Interceptors ❌ βœ…
Timeout ❌ βœ…
Response Errors Manual Automatic
Lightweight βœ… ❌ (external dependency)

🎁 Bonus: Fetch Wrapper for Reusability

const fetchJson = async (url, options = {}) => {
  const response = await fetch(url, options);
  if (!response.ok) throw new Error(`Error: ${response.status}`);
  return await response.json();
};
Enter fullscreen mode Exit fullscreen mode

🧩 Conclusion

The Fetch API is a modern, native way to interact with HTTP resources β€” whether it's creating, reading, updating, or deleting data.

βœ… Use Fetch for:

  • Lightweight and browser-native HTTP calls
  • Simple use cases where you don’t need interceptors or advanced features

❗ Use Axios if you:

  • Need advanced features like interceptors, request cancellation, or automatic transformation

Top comments (1)

Collapse
 
ravavyr profile image
Ravavyr

unpopular opinion:

Only use GET [for anything without parameters] and POST for everything else.
This reduces the request processing you have to do server side and the number of types of requests you need to secure and worry about.

The examples all assume json is returned... this is not always the case though some would have you think it to be "standard". Nothing is standard on the internet, learn about content types.

No point in comparing Fetch vs Axios. Axios is a library, Fetch is a standard method in Javascript.
You don't need Axios if you know how to use Fetch, thereby reducing on more dependency in your pile of dependencies.

The handle http errors manually assumes "response.ok" always exists. It does not.
Your server/endpoint code has to generate the response object and you can literally make it say "bob" if you want to.
Look for the status code 200 and go by that and use values returned as a secondary validation.