Background parttern

Fetch API vs Axios for HTTP requests

Fetch API vs Axios for HTTP requests which one is better and why?

HTTP / HTTPSAPIRequestCommunication

Fetch API

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across a network.

Syntax

fetch.ts

fetch(input, init)

Parameters

  • input - The URL you wish to fetch.
  • init - An object with any custom settings that you want to apply to the request. The possible options are:
    • method - The request method, e.g., GET, POST, PUT, PATCH, DELETE. The default is GET.
    • headers - Any headers you want to add to your request, contained within a Headers object or an object literal with ByteString values.
    • body - Any body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that a request using the GET or HEAD method cannot have a body.
    • mode - The mode you want to use for the request, e.g., cors, no-cors, same-origin, or navigate. The default is cors which stands for Cross-Origin.
    • credentials - The request credentials you want to use for the request: omit, same-origin, or include. The default is same-origin.
    • cache - The cache mode you want to use for the request: default, no-store, reload, no-cache, force-cache, or only-if-cached.
    • redirect - The redirect mode to use: follow, error, or manual. The default is follow.
    • referrer - A USVString specifying no-referrer, client, or a URL. The default is client.
    • referrerPolicy - Specifies the value of the referer HTTP header. May be one of no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, or unsafe-url.
    • integrity - Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAeHtYK7DDiZ0L+FL/4vow=).

Example

TRY-CATCH METHOD

The try catch method is an efficient way to handle errors in code. Using the fetch API with a try-catch block is a good way to implement error handling with the fetch API because more can be done and it can ensure clean and a readable code.

Using the {JSON} Placeholder API, we can fetch data from the API and handle errors with the try-catch method.

try-catch-method.ts

type ErrorCause = Error & {
  cause?: { error: Error; response: Response }
}
 
try {
  // Fetch data from the API
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
    method: 'GET', // method can be GET, POST, PUT, PATCH, DELETE depending on the API endpoint definition
    mode: 'cors', // mode to use for request
    headers: {
      Authorization: `Bearer ${token}`, // Add token to the header if needed for authentication and authorization
      'Content-Type': 'application/json'  // Add content type if needed
    },
  })
 
  // Check if the response is ok and throw an error to the catch block if not
  if (!response.ok) throw new Error('Something went wrong', { cause: { response } })
 
  // perform some action with the response
  // make toast notification
 
  // Parse the response to JSON
  const data = await response.json()
 
  // do something with the data
} catch (error) {
  let err: ErrorCause
 
  if (error instanceof Error) err = error as ErrorCause
  else err = new Error('Error fetching todo', { cause: { error } }) as ErrorCause
 
 
  // since the error was thrown from the try block with the response object, we can access the response object from the error object
  // Handle errors based on the status code
  switch (err.cause?.response?.status) {
    case 400: // bad request - invalid data
      // perform some action
      break
 
    case 401: // unauthorized - invalid token
      // perform some action
      break
 
    // others
    default:
      // perform some action
      break
  }
}

USING THE PROMISES-CHAIN METHOD

The promises-chain method is another way to use the fetch API. This method is not as efficient as the try-catch method because it is not as readable and might not be as clean as the try-catch method.

promises-chain-method.ts

// Fetch data from the API
fetch('https://jsonplaceholder.typicode.com/todos/1', {
  method: 'GET', // method can be GET, POST, PUT, PATCH, DELETE depending on the API endpoint definition
  mode: 'cors', // mode to use for request
  headers: {
    Authorization: `Bearer ${token}`, // Add token to the header if needed for authentication and authorization
    'Content-Type': 'application/json'  // Add content type if needed
  },
})
  .then((response) => {
    // Check if the response is ok and throw an error to the catch block if not
    if (!response.ok) throw new Error('Something went wrong', { cause: { response } })
 
    // perform some action with the response
    // make toast notification
 
    // Parse the response to JSON
    return response.json()
  })
  .then((data) => {
    // do something with the data
  })
  .catch((error) => {
    let err: ErrorCause
 
    if (error instanceof Error) err = error as ErrorCause
    else err = new Error('Error fetching todo', { cause: { error } }) as ErrorCause
 
    // handle
  })

Axios

Axios is a promise-based HTTP client for the browser and Node.js. It has a convenient and modern API simplifying asynchronous HTTP request and response handling.

Syntax

axios.ts

axios(url, config)