DEV Community

Cover image for Javascript Fetch example: Get/Post/Put/Delete
Tien Nguyen
Tien Nguyen

Posted on • Edited on • Originally published at bezkoder.com

Javascript Fetch example: Get/Post/Put/Delete

JavaScript Fetch API provides an interface for accessing and manipulating HTTP requests and responses. In this tutorial, we will create examples that use Javascript fetch() method to make Get/Post/Put/Delete request. The final section shows a simple Fetch HTTP Client to interact and get data from Rest API in Javascript.

Related Posts:

Full Article at BezKoder

Javascript Fetch Overview

Javascript Fetch API has a global fetch() method that provides way to fetch resources asynchronously across the network.
fetch() returns a Promise that resolves with a Response object, which is fulfilled once the response is available.



const responsePromise = fetch(resourceUrl [, options]);


Enter fullscreen mode Exit fullscreen mode

A basic fetch request will look like this::



fetch('/bezkoder.com/data')
  .then(response => response.json())
  .then(data => console.log(data));


Enter fullscreen mode Exit fullscreen mode

Javascript Fetch Response Data

The Response object we mention above represents the entire HTTP response, it does not directly contain the response body. To get the actual JSON body of the response, we use following methods:

Javascript Fetch Response Metadata

We can also access metadata such as headers, status, statusText, type, url from the Response object:



fetch('/bezkoder.com/data').then(function(response) {
    console.log(response.headers.get('Content-Type'));
    console.log(response.headers.get('Date'));

    console.log(response.status);
    console.log(response.statusText);
    console.log(response.type);
    console.log(response.url);
});


Enter fullscreen mode Exit fullscreen mode

Fetch error handling

The response Promise does not reject on HTTP errors (for example: 404, 500). It only rejects when encountering a network error. So we must use then() to check for HTTP errors with response.ok status and/or response.status properties.



fetch('/bezkoder.com/data')
  .then(function(response) {
    // if (response.status !== 200)
    if (!response.ok) {
       console.log('Error with Status Code: ' + response.status);
       return;
    }

    response.json().then(function(data) {
      console.log(data);
    });
  })
  .catch(function(err) {
    console.log('Error: ' + err);
  });


Enter fullscreen mode Exit fullscreen mode

Fetch try catch async-await

If you want to use async-await, just wrap the fetch call with try/catch block.



async function getData() {
  try {
    const response = await fetch('/bezkoder.com/data');

    if (!response.ok) {
      const message = 'Error with Status Code: ' + response.status;
      throw new Error(message);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log('Error: ' + err);
  }
}


Enter fullscreen mode Exit fullscreen mode

Fetch with params

You can use URL object with URLSearchParams to set query string params.



let url = new URL('/bezkoder.com/data');
const params = { title: 'web'};
url.search = new URLSearchParams(params);

try {
  const response = await fetch(url);

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}


Enter fullscreen mode Exit fullscreen mode

And this is equivalent:



const response = await fetch('/bezkoder.com/data?title=web');


Enter fullscreen mode Exit fullscreen mode

Fetch with headers

To send Fetch request with Headers, we pass an option object with method and headers property.



const options = {
  method: 'get',
  headers: {
    "Content-Type": "application/json",
    "x-access-token": "token-value",
  }
};

try {
  const response = await fetch('/bezkoder.com/data', options);

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}


Enter fullscreen mode Exit fullscreen mode

Javascript Fetch POST

Fetch POST Form data

Let's create a POST request with Formdata in the body of the request.



let formData = new FormData();
formData.append('title', 'BezKoder Tutorial');
formData.append('description', 'Tut Desc');

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "post",
    // headers: {
    //   "Content-Type": "application/x-www-form-urlencoded"
    // },
    body: formData
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}


Enter fullscreen mode Exit fullscreen mode

If you use application/x-www-form-urlencoded, the keys and values are encoded in key-value tuples.

Fetch POST JSON

Let's create a POST request with JSON.

We use JSON.stringify() on the object before passing it in the body of the request and set application/json for the header Content-Type.



const postData = {
  title: title,
  description: description,
};

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(postData)
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}


Enter fullscreen mode Exit fullscreen mode

Fetch POST file

Working with file is similar with previous one by using Form data.



let formData = new FormData();
// formData.append('title', 'BezKoder Tutorial');
// formData.append('description', 'Tut Desc');
formData.append('file', file);

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "post",
    body: formData
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}


Enter fullscreen mode Exit fullscreen mode

We don't need to set the Content-Type header with multipart/form-data. The browser will automatically choose the appropriate content type header including form boundary.

Javascript Fetch PUT

Now we're gonna generate Fetch PUT example with JSON data. It's similar to Fetch POST request:

  • method: "put"
  • "Content-Type": "application/json"
  • using JSON.stringify() on the object


const postData = {
  title: title,
  description: description,
};

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "put",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(postData)
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}


Enter fullscreen mode Exit fullscreen mode

Fetch DELETE example



try {
  const response = await fetch('/bezkoder.com/data/42', {
    method: "delete"
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}


Enter fullscreen mode Exit fullscreen mode

Javascript Fetch example with Rest API

We will build a HTTP Client to make CRUD requests to Rest API in that:

  • Fetch GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title
  • Fetch POST request: create new Tutorial
  • Fetch PUT request: update an existing Tutorial
  • Fetch DELETE request: delete a Tutorial, delete all Tutorials

javascript-fetch-api-tutorial-example

This Fetch Client works with the following Web API:

Methods Urls Actions
POST /api/tutorials create new Tutorial
GET /api/tutorials retrieve all Tutorials
GET /api/tutorials/:id retrieve a Tutorial by :id
PUT /api/tutorials/:id update a Tutorial by :id
DELETE /api/tutorials/:id delete a Tutorial by :id
DELETE /api/tutorials delete all Tutorials
GET /api/tutorials?title=[keyword] find all Tutorials which title contains keyword

You can find step by step to build a Server like this in one of these posts:

For more details, please visit:
https://www.bezkoder.com/javascript-fetch/

Conclusion

With this Javascript Fetch tutorial, you've known many ways to make GET/POST/PUT/DELETE request using Fetch API (with headers, params, body, form data...). You also know how to handle error in Fetch request or use async/await with try/catch statement.

Instead of Fetch API, you can also use Axios which is a promise-based HTTP Client Javascript library for Node.js and Browser. Kindly visit:
Axios Tutorial: Get/Post/Put/Delete request example

Happy Learning! See you again.

Further Reading

Using Fetch with React:
React Fetch example with Rest API

With Vue:
Vue Fetch example with Rest API

You can apply it in one of following React/Vue applications (using fetch instead of axios):

Top comments (0)