DEV Community

FranciscoBenjamn
FranciscoBenjamn

Posted on

How'd we access our Api

****

Honestly speaking, Javascript has to be one of the most widely known coding languages out there. It's a common jumping point from learning HTML and CSS. Starting my journey through Flatiron with Javascript, I was nervous at first since it had been a very long time since I had dealt with any type of code, about 2 years

Project #1

Okay let's get into the main topic of this blog, my first major Javascript project.

Welcome to 'Who's Funnier'

You might be wondering where we got our jokes from. I accessed these jokes from an api using this line of code

//Code for our api. function we will be using with fetch to get information from api
const BASE_URL = "https://v2.jokeapi.dev/joke/Any?amount=2"
Enter fullscreen mode Exit fullscreen mode

and to retrieve the resources from our api we use fetch

//Code for our 'Start Now' button. Asynchronously fetches jokes from our api through use of a promise.
startButton.addEventListener('click', async () => {
//If we're able to retrieve our jokes from api, present them in json.
    const data = await fetch(BASE_URL)
        .then((response) => response.json())
//If not then report an error message in our console
        .catch((error) => console.error(error))
Enter fullscreen mode Exit fullscreen mode

Now three key words we have here are fetch, async, and await. When it comes to making network in web applications, Fetch is our goto. In our code, fetch sends out a request from our joke api to use their information and returns a response from the api to our request. Should there ever be a problem with connecting with our api, we'd receive an error message within our console Next comes our async function. The process behind it is simple, it allows us to run our program without it being blocked. Finally, await is a function that can be run in an async function. Essentially it has our code wait till the promise of our request is fulfilled. Together, all of these allow us to access information from our api's to utilize them in our further code.

Top comments (0)