Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Calling the API

Define An async Function

info

async means this function can use await inside it.

tip

  async function nameOfFunction()

try block

info

  • This is where you put code that might fail (we will talk about how to handle the fail in the next section), in this case your API Call.

tip

   try {
       ...
   }

Send A Request to the API

info

  • fetch(...) sends a GET request to the URL.
  • await means "wait for the response before continuing."

tips

       const response = await fetch('<url of your API>');

Parse the JSON Response

info

The API returns something like:

   {
   "data": ["Response from AI"]
   }
  • await response.json() reads the body of the response and turns it into a JavaScript object.
  • The result is stored in the data variable.

tips

   const data = await response.json();

info

  • data.data is an array of facts.
  • data.data[0] gives you the first fact.

tip

  console.log(...);