Fetch Web API

fetch usage

The fetch() function returns a Promise<Response> (a promise that resolves to a Response object).

The Response.json() method returns a Promise that resolves the object produced by parsing the JSON content of the body.

fetch('https://www.googleapis.com/books/v1/volumes?q=extreme%20programming')
    .then(response => response.json())
    .then(data => console.log(data));

Or using async/await:

const response = await fetch('https://www.googleapis.com/books/v1/volumes?q=extreme%20programming');
const data = await response.json();
console.log(data);

fetch options

The second argument for the fetch function is an options object that allows you for instance to send POST requests or to control additional stuff in the request like HTTP headers.

const book = {
    id: 'BOOK_ID',
    title: 'eXtreme Programming explained'
};

fetch('https://api.mylibrary.io/books', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify(book)
});

Last updated