Learn JS Async/Await, Fetch Requests & APIs by Building a Trivia Game
Tags: javascript, tutorial, beginners, programming
Published: 2022-01-13 00:17:12

> This tutorial is available as a [free Series on CodeCast](https://www.codecast.io/series/61-learn-api-s-building-a-trivia-game-w-javascript)!

API's are intimidating when you're learning to code, especially ones that come with really complicated docs, needs unique keys, or require authorization.

Instead of jumping headfirst into a whirlpool, we're gonna wade in slowly into the world of API's by using a free and extremely simple API from [Open Trivia DB](https://opentdb.com/). 

We're also going to go over making requests from the API using JavaScript's fetch requests while making use of await/async.

You can find the entire collection of Casts in a [free Series on CodeCast](https://www.codecast.io/series/61-learn-api-s-building-a-trivia-game-w-javascript). The Casts contain both the video tutorials and all the code that is written, so it's very much worth checking out!

### Step One - Connect The API

{% youtube tvPL6C-C-wI %}

In this section, we're going to connect to the API. You can watch it on [the Player](https://play.codecast.io/wn95BRNO5dm1-trivia-game-connecting-to-the-open-trivia-api?t=0) where you can access the code, or watch just the tutorial portion above!

#### Grabbing the API URL

This API is incredible simple. It doesn't require tokens or any unique identifier. You simply provide the URL and make your requests directly to the API following their conventions.

We start by creating the `.js` file we will be writing all our code in, which I named "app.js".

Inside, we're assigning the url we retrieved from the API to a variable. Note that the API has a 'helper' that lets you build the unique url to contain specifically what you want. 

![API Helper](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rco42q1f112vlv3avas.png)
 
These are the specifications I use to get the URL below:

      const url = 'https://opentdb.com/api.php?amount=100';

Now we can begin building out our fetch request. We'll start with the shell of the function:

     function getTrivia() {
     }

Inside the function, we're going to want to make a request to the url. Once we get a response from the API, we can then make use of the data that we returned:

     function getTrivia() {
       let response = fetch(url);
       let data = response.json();
       return data;
     }

However, if we were to run the function above, we would get some big problems. The code will run too quickly for the data to be retrieved by the time we're asking for it. We will not be able to be use to `.json()` to parse the response as it won't exist yet. This is where `async/await` comes in.

We will begin by placing the `async` keyword at the very beginning before the function declaration. This simply signifies that the function will always return a Promise. If you're not familiar with Promises, you can read up on them [here](https://javascript.info/promise-basics).

So now our function will look like this:

     async function getTrivia() {
       let response = fetch(url);
       let data = response.json();
       return data;
     }

Now, we use the `await` keyword to ensure that JavaScript waits until that specific Promise is fulfilled and returns its results. We want to use it in *two* places within our function. Most critically, we want to use it to ensure that we don't move forward with parsing the response until the response exists. In other words, we want to add it to our `fetch` request.

We also want to add it to our parse request so our `data` is for sure parsed before it gets returned to us. Once those are done, we will return the `data` as normal. Our function now looks as follows:

     async function getTrivia() {
       let response = await fetch(url);
       let data = await response.json();
       return data;
     }

Now, we'll call the function to retrieve the data. But what do we do with that data? Because it's a Promise, we can use then `.then()` chaining method on the function to tell our application what we want to do next. In this case, we're simply going to just console.log out our data so we can ensure that our function is running smoothly. This call will look like this:
 
     getTrivia().then((data) => console.log(data.results));

With the result producing:

![Data Results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wm8yx1q79hfbyq6onxp6.png)
 
Now that we have our API connected properly, we can begin building out the rest of the application! To find the rest of the content, you can watch them on [my CodeCast Channel](https://www.codecast.io/users/amy), by purchasing my [free Series](https://www.codecast.io/series/61-learn-api-s-building-a-trivia-game-w-javascript), or on [YouTube](https://www.youtube.com/playlist?list=PL5egNEXQTWmFHAoWFVRLNAvD-9zzyWVxA) (code not available for copying on YouTube). 

Happy Coding 👩🏻‍💻

For more of my content, follow me on like [Twitter](https://twitter.com/amyeoulton) & [CodeCast](https://www.codecast.io/users/amy)! 

You can also read my last blog here:
{% link https://dev.to/amyoulton/how-to-create-a-random-number-generator-w-javascript-4ikf %}.