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.
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]);
A basic fetch request will look like this::
fetch('/viastudy.com/data')
  .then(response => response.json())
  .then(data => console.log(data));
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:
response.arrayBuffer(): returns a promise that resolves with an ArrayBuffer.
response.blob(): returns a Promise that resolves with a Blob.
response.error(): returns a new Response object associated with a network error.
response.formData(): returns a Promise that resolves with a FormData.
response.json(): returns a Promise that resolves with the result of parsing as JSON.
response.text(): returns a Promise that resolves with a text.
Javascript Fetch Response Metadata
We can also access metadata such as headers, status, statusText, type, url from the Response object:
fetch('/viastudy.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);
});
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('/viastudy.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);
  });
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('/viastudy.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);
  }
}
Fetch with params
You can use URL object with URLSearchParams to set query string params.
let url = new URL('/viastudy.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);
}
And this is equivalent:
const response = await fetch('/viastudy.com/data?title=web');
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('/viastudy.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);
}
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', 'viastudy Tutorial');
formData.append('description', 'Tut Desc');
try {
  const response = await fetch('/viastudy.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);
}
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('/viastudy.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);
}
Fetch POST file
Working with file is similar with previous one by using Form data.
let formData = new FormData();
// formData.append('title', 'viastudyTutorial');
// formData.append('description', 'Tut Desc');
formData.append('file', file);
try {
  const response = await fetch('/viastudy.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);
}
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('/viastudy.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);
}
Fetch DELETE example
try {
  const response = await fetch('/viastudy.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);
}
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
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

#viastudy

Post a Comment

0 Comments