This page is a work in progress.You can help improve it. →

Fetch api

The Fetch API provides an interface for fetching resources, primarily across the network.

Basic usage:

fetch('https://restcountries.eu/rest/v2/all')
.then(response => {
return response.json()
})
.then(apiData => {
console.log(apiData)
})

Basic usage with async/await

async function countries() {
const response = await fetch('https://restcountries.eu/rest/v2/all')
if (response.ok) {
const apiData = await response.json()
console.log(apiData)
}
}

Using a specific http verb (e.g. POST)

async function createOneListItem() {
const response = await fetch(
// URL
'https://one-list.herokuapp.com?access_token=illustriousvoyage',
// Options
{
// This is a POST request
method: 'POST',
// We are sending JSON
headers: { 'content-type': 'application/json' },
// The body of the message is the object, but turned into a string in JSON format
body: JSON.stringify({
item: { text: 'Learn about Regular Expressions!' },
}),
}
)
if (response.ok) {
// Process the response
const apiData = await response.json()
}
}
© 2017 - 2021; Built with ♥ in St. Petersburg, Florida.