Blog/NotesConcept

Ultimate guide to REST API calls using Fetch: Machine Coding Essential

You will get a clear understanding about working with any rest api and common concepts asked during interviews

Beginner

Vivek Chavan

Last Updated Mar 7, 2025


REST APIs allow communication between client and server using HTTP methods like GET, POST, PUT, PATCH, and DELETE. The fetch API is a modern way to handle HTTP requests in JavaScript, providing a promise-based approach to fetch resources from the network.

Understanding the Basics of Fetch

What is the fetch API?

The fetch API is a native JavaScript function for making network requests, returning a promise that resolves the response of the request.

How does fetch work in JavaScript?

It initiates a network request and returns a promise, which can be resolved to handle the response or rejected in case of errors.

javascript fetch call flow

Basic syntax and an example of a simple GET request:

The below code fetches a list of dog breeds, converts it into JSON, and logs into the console.
It logs an error in case the API fails because of any error from the server side or any network error.

Example:

fetch('https://dog.ceo/api/breeds/list/all')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Different HTTP Calls using fetch()

1. GET API Call Using fetch()

Basic GET Request Example:

fetch('https://dog.ceo/api/breeds/list/all')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Fetch error:', error));
 

2. POST API call using fetch()

The POST method is used to send data to the server to create or update a resource.

Basic POST request with fetch

The code below represents a POST call with an object payload to create a blog post

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

3. PUT/PATCH API Calls Using fetch()

PUT vs PATCH: PUT is used to update an entire resource, while PATCH is used to update only a part of the resource.

PUT example using fetch()

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    id: 1,
    title: 'foo',
    body: 'bar',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Patch example using fetch()

// PATCH request to update a specific field
fetch('<https://jsonplaceholder.typicode.com/posts/1>', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ title: 'foo' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Note: 

The difference between "PUT" and "PATCH" is that PUT is Idempotent. 
Repeat PUT API calls multiple times have No Effect on the data store, in contrast to the PATCH call, where multiple patch calls may impact the data store. 

4. DELETE API Calls Using fetch()

The DELETE HTTP method is used to remove a resource from a list of resources.

Basic DELETE request example using fetch:

In the below example, the DELETE call deletes a post with Id 1 on successful execution otherwise it will throw an Error "Failed to delete resource."

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'DELETE'
})
  .then(response => {
    if (response.ok) {
      console.log('Resource deleted successfully');
    } else {
      throw new Error('Failed to delete resource');
    }
  })
  .catch(error => console.error('Error:', error));

Parallel API Calls:

Parallel API calls play a very important role in improving the performance of the web application by parallelly calling multiple API calls simultaneously. In this approach, client should not wait for one after the other API call to complete and overall reduce the time to fetch the resources from the server. 

This is an important concept to know for frontend machine coding rounds, where unrelated API calls should be called using fetch & Promise.all() to improve the overall application performance and response time.

Here is an example, where using fetch() and Promise.all() we can fetch both breeds and random dog images simultaneously.

const breedListUrl = 'https://dog.ceo/api/breeds/list/all';
const randomDogImageUrl = 'https://dog.ceo/api/breeds/image/random';

Promise.all([
  fetch(breedListUrl).then(response => response.json()),
  fetch(randomDogImageUrl).then(response => response.json())
])
.then(results => {
  const [breeds, randomImage] = results;
  console.log('Breeds:', breeds);
  console.log('Random Dog Image:', randomImage);
})
.catch(error => console.error('Error with parallel fetch:', error));

Retrying Failed fetch() API Calls:

In general, this is a best practice to have a retry mechanism enabled for API calls so that if in case there is a REST API call fails due to some network issue or some server internal error, That issue can be resolved with retry mechanisms.

Note: Retry is a nice-to-have feature while building applications with API calls in frontend machine coding rounds.

In the below example, we can have a common function (ex- fetchWithRetry(URL, options, retries = MAX_RETRIES) ) which triggers the API call "n" number of retries if there is any failure.

 
function fetchWithRetry(url, options = {}, retries = 3) {
  return fetch(url, options).catch(error => {
    if (retries > 0) {
      console.log(`Retrying... (${retries} left)`);
      return fetchWithRetry(url, options, retries - 1);
    } else {
      throw error;
    }
  });
}

fetchWithRetry('https://dog.ceo/api/breeds/list/all')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Final fetch error:', error));
Retry Flow

ā­ Follow-up concepts to learn :

  • Why do we use fetch over Axios?
  • Reason behind the CORS error while having API calls and how to resolve it?

šŸš€

Love this content? Share it!

Help others discover this resource

About the Author

Vivek Chavan

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

Share Your Expertise & Help the Community!

Build Your Portfolio

Help the Community

Strengthen Your Skills

Share your knowledge by writing a blog or quick notes. Your contribution can help thousands of frontend developers ace their interviews and grow their careers! šŸš€


Other Related Blogs

Call, apply, and bind in JavaScript: Examples & Polyfills

Kirtesh Bansal

Last Updated Feb 21, 2026

A beginner-friendly guide to understanding call, apply, and bind methods in JavaScript, along with step-by-step call, apply and bind polyfill implementations that are often asked in interviews.

Implementing a stopwatch using React - Frontend Machine Coding Question

Pallavi Gupta

Last Updated Feb 21, 2026

Concise explanation of stopwatch implementation using React, it involves the usage of useEffect hook for creating a stopwatch and tracking milliseconds.

setTimeout Polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Aug 3, 2025

Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.

Implement useSessionStorage() Custom Hook in React [Interview]

Anuj Sharma

Last Updated Nov 15, 2025

Understand the code implementation of useSessionStorage custom hook in react that will help to efficiently manager session storage in application.

Top 10 React Performance Optimization Techniques [React Interview]

Anuj Sharma

Last Updated Feb 21, 2026

Find the top React Performance Optimization Techniques specific to React applications that help to make your react app faster and more responsive for the users along with some bonus techniques.

Implement useToggle() Custom Hook in React (Interview)

Anuj Sharma

Last Updated Feb 21, 2026

Explore code explanation of useToggle() custom hook in react to handle the toggle event efficiently.

Stay Updated

Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

All in One Preparation Hub to Ace Frontend Interviews. Master JavaScript, React, System Design, and more with curated resources.

Consider Supporting this Free Platform

Buy Me a Coffee

Product

HomeFrontend InterviewInterview ExperienceBlogsToolsLeaderboard

Tools

CSS Image FilterPixelate ImageAspect Ratio CalculatorBox Shadow GeneratorCSS Gradient GeneratorNeumorphism GeneratorExplore More Tools →

Ā© 2026 FrontendGeek. All rights reserved