Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Javascript - Web APIs

Back


Web API


Fetch API


HTTP Structure


XMLHTTPRequest


fetch()

// syntax
fetch(resource).then();
fetch(resource, options).then();

// common use
// define an async function
async function postData(url = "", data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, *cors, same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: "follow", // manual, *follow, error
    referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

// call the async function
postData("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON data parsed by `data.json()` call
});
<script>
  // promise
  const JSON_URL = "books.json";

  console.log("Json:Fecth promise");

  fetch(JSON_URL)
    .then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        throw Error(response.statusText);
      }
    })
    .then((json_data) => console.log("Json promise:", json_data))
    .catch((err) => console.log("Error", err));

  // async
  console.log("Json:Fecth async");

  const main_fetch_async = async (url) => {
    const json_data = await fetch(url).then((response) => response.json());
    console.log("Json Async:", json_data);
  };
  main_fetch_async(JSON_URL);
</script>

Example

console.log("\n-------- fetch(): Example --------\n");

const CLIENT_ID = "910e59ec1184482d8932ab9e1bc3ff8d";
const CLIENT_SECRET = "02f3d3633013444f86f33305092dcfb5";

const URL_TOKEN = "https://accounts.spotify.com/api/token";
const URL_GENREUS = "https://api.spotify.com/v1/browse/categories?locale=sv_US";
("https://api.spotify.com/v1/browse/categories/{category_ID}/playlists");

// define an async function to get token.
const getToken = async (urlToken, clientID, clientSecret) => {
  const response = await fetch(urlToken, {
    method: "POST",
    headers: {
      Authorization: `Basic ${btoa(clientID + ":" + clientSecret)}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: "grant_type=client_credentials",
  });

  const data = await response.json();
  return data.access_token;
};

// define an async function to get genre list.
const getGenreList = async (urlGenre, token, genreLimit = 10) => {
  const reponse = await fetch(urlGenre + "&limit=" + genreLimit, {
    method: "GET",
    headers: {
      Authorization: "Bearer " + token,
    },
  });
  const data = await reponse.json();
  return data.categories.items;
};

// define a main funciont to display genre names.
const main = async () => {
  let token = await getToken(URL_TOKEN, CLIENT_ID, CLIENT_SECRET);
  let genreList = await getGenreList(URL_GENREUS, token);

  for (let obj of genreList) {
    console.log(obj["name"]);
  }
};

// call main function
main();
// Topplistor
// Hiphop
// Pop
// Sommar
// Country
// Rock
// Humör
// Träning
// Chill
// R&B

TOP