Home

Fetch Requests

The Fetch API is a modern replacement for XMLHttpRequest

My course has a few documents that they recommend taking a look at.
So I have listed a few here:-

FETCH a beginners guide

And a basic document from w3Schools can be found HERE

Another document that may be useful is about {cache: "..."}
eg: fetch(url, {cache: "no-cache"})


And a few MDN documents that may be useful:-

AJAX - Getting Started - can be found HERE
Fetching Data from the Server - can be found HERE
Using Fetch - can be found HERE
Third-party APIs - can be found HERE

Top

The Fetch API interface allows web browsers to make HTTP requests to web servers.
With no need for XMLHttpRequest anymore.

A quick example of this, for GETting the information could be...

//sends request
//Note .then() will ONLY fire after the promise status
//of fetch() has been resolved

fetch('http://api-to-call.com/endpoint')

   .then(response => {

      
//converts response to JSON
      if (response.ok) {
      
//(The reason we’re testing the ok
      //property of the response object
      //is that it will be a Boolean value.
      //If there were no errors response.ok will be true and then
      //your code will return response.json() - this
      //will then get passed on to the next .then()

         return response.json();
      };

      
//handles Errors
      // If there was an error with response.json
      // then create the message to be viewed

      throw new Error('Request Failed!');

   }, networkError => {
      
// If we could not reach the endpoint at all,
      // e.g., the server is down, then we would get
      // this networkError.
      // If there was an error then run this

      console.log(networkError.message)
   })
// this is the end of the first .then()

   
//handles Success
   // It won’t run until the previous .then() method has
   // finished running.
   // (the response.json value from the previous
   // .then() is used and saved as 'jsonResponse).
   // It will also not run if there was
   // an error thrown previously.

   .then(jsonResponse => {
      
// Code to execute with jsonResponse...
      return jsonResponse;
   });
// this is the end of the second .then()


Fetch Requests (POST)

NOTE...
This uses stringify

A quick example of this, for POSTing the information could be...

//sends request
//Note .then() will ONLY fire after the promise status
//of fetch() has been resolved

fetch('http://api-to-call.com/endpoint', {
   method: "POST",
   body: JSON.stringify({id: "200"})

   .then(response => {

      
//converts response to JSON
      if (response.ok) {
      
//(The reason we’re testing the ok
      //property of the response object
      //is that it will be a Boolean value.
      //If there were no errors response.ok will be true and then
      //your code will return response.json() - this
      //will then get passed on to the next .then()

         return response.json();
      };

      
//handles Errors
      // If there was an error with response.json
      // then create the message to be viewed

      throw new Error('Request Failed!');

   }, networkError => {
      
// If we could not reach the endpoint at all,
      // e.g., the server is down, then we would get
      // this networkError.
      // If there was an error then run this

      console.log(networkError.message)
   })
// this is the end of the first .then()

   
//handles Success
   // It won’t run until the previous .then() method has
   // finished running.
   // (the response.json value from the previous
   // .then() is used and saved as 'jsonResponse).
   // It will also not run if there was
   // an error thrown previously.

   .then(jsonResponse => {
      
// Code to execute with jsonResponse...
      return jsonResponse;
   });
// this is the end of the second .then()


Top

Here is another little example of how async/await and fetch can be used...

//create an anonymouse function (arrow function)
//saved to a const getData.
// The async keyword will ensure that the 
// function returns a promise. 
const getData = async () => {
  try { 

                //We’ll have to save the returned promise 
    //in a variable 
    //called response using the const keyword. 
    //response will save the response of 
    //endpoint once 
    //that information has been sent back. 
                const response = await fetch(
      "https://api-to-call.com/endpoint"); 

                //Create a conditional statement that 
    //checks if the ok property 
    //of the response object evaluates to 
    //a truthy value. 
                if (response.ok) { 

                //Since .json() is an asynchronous 
      //method we have to await 
      //until the promise status is resolved. 
      //Then we store the value to know what 
      //data the JSON holds. 
                const jsonResponse = await response.json(); 

                //Normally, we’d want to use the 
      //information from 
      //jsonResponse in a different manner. 
      //but for now just return the result 
                return jsonResponse;
    } 
    
                //If it fails create your error message 
                throw new Error('Request failed!'); 

  } catch (error) { 
                //Since this exercise is an example, 
    //we’re using 
    //console.log() to view the error. 
    //Generally, developers create a 
    //more sophisticated way 
    //of handling the error, 
    //like redirecting their 
    //users to another page 
                console.log(error);
  }
} 


And this partial example consists of the code for one form (would be called main.js).
It also uses a file called 'helperFunctions.js' but I have not included it here as it will be pretty much the same as what is already present in the 'HTTPRequest' folder for the other projects.
So if you want to then take a look there.

The project also used a file which is very similar, if not the same, as rebrandly_HTTPRequests.html so I am not including that either.
I am not running this as a working example I just wanted to show the code that did change a bit and that is below...

// information to reach API
const apiKey = 'ENTER YOUR REBRANDLY API KEY IN HERE';
const url = 'https://api.rebrandly.com/v1/links';

// Some page elements that are on HTTPRequests.html
const inputField = 
    document.querySelector('#input');
const shortenButton = 
    document.querySelector('#shorten');
const responseField = 
    document.querySelector('#responseField');

// AJAX functions
// Code goes here
const shortenUrl = async () => {
  const urlToShorten = inputField.value;
  const data = JSON.stringify({destination: urlToShorten});
  try {
    const response = await fetch(
      url, 
      {method: 'POST', 
      body: data,
      headers: {'Content-type': 'application/json',
'apikey': apiKey}
    }
    );

    if (response.ok) {
      const jsonResponse = await response.json();
      renderResponse(jsonResponse);
    }
  } catch (error) {
    console.log(error);
  };
};

// Clear page and call AJAX functions
const displayShortUrl = (event) => {
  event.preventDefault();
  while(responseField.firstChild){
    responseField.removeChild(responseField.firstChild);
  }
  shortenUrl();
}

shortenButton.addEventListener('click', displayShortUrl);

Top

A quick recap

  1. GET and POST requests can be created a variety of ways.
  2. Use AJAX to asynchronously request data from APIs. fetch() and async/await are new functionalities developed in ES6 (promises) and ES8 respectively.
  3. Promises are a new type of JavaScript object that represent data that will eventually be returned from a request.
  4. fetch() is a web API that can be used to create requests. fetch() will return promises.
  5. We can chain .then() methods to handle promises returned by fetch().
  6. The .json() method converts a returned promise to a JSON object.
  7. async is a keyword that is used to create functions that will return promises.
  8. await is a keyword that is used to tell a program to continue moving through the message queue while a promise resolves.
  9. await can only be used within functions declared with async.


An example: Using two API calls

The APIs used are from
Foursquare.com
Openweathermap.org


API Keys provided by the two companies will be required to run the page
I have my own keys but cannot hard code them in the form.


The files used for this example are as follows:-

fourWeather.html
/HTTPRequest/fourWeather_helper.js
/HTTPRequests/fourWeather_main.js


To run this example Click Here

Top