/
Write
Start a team blog
NEW ✨
Start a team blog, invite your team, and start publishing.
Here is a course that shows how to make a simple API calls with the fetch() method in Javascript

Here is a course that shows how to make a simple API calls with the fetch() method in Javascript

William Quesnot's photo
William Quesnot
·Jan 16, 2022·

2 min read

First, get the API you want to fetch

Example :

https://api.thecatapi.com/v1/images/search

and pass it preferably under a variable, you will understand why

Example : 

let apiCat = 'https://api.thecatapi.com/v1/images/search'; 
// I took the API in a variable

Create a function allowing to fetch the API by setting the url in parameters, by this function you will be able to fetch several APIs when it will be necessary. Remember you have to do an asynchronous function, it is a function that runs asynchronously with a promise

The await operator allows to wait the promise to be resolved. It can only be used within an asynchronous function

let apiCat = 'https://api.thecatapi.com/v1/images/search'; 

const getApi = async (url) => {
        const response = await fetch(url)

}

Now you have fetch an API but to be able to manipulate it, you have to convert it to json format

let apiCat = 'https://api.thecatapi.com/v1/images/search'; 

const getApi = async (url) => {
        const response = await fetch(url)
        const data = await response.json()
}

Then return the data

let apiCat = 'https://api.thecatapi.com/v1/images/search'; 

const getApi = async (url) => {
        const response = await fetch(url)
        const data = await response.json()
        return data
}

Now by doing a console.log you will be able to see what data return

let apiCat = 'https://api.thecatapi.com/v1/images/search'; 

const getApi = async (url) => {
        const response = await fetch(url)
        const data = await response.json()
        console.log(data) 
}

You did a console.log(data), this is what you get

line4.png

Making a function to fetch an API will allow you to avoid any error and to know if the code works,so it is recommended to make a function to fetch the API and another separate function to display the Api.

Now that you have fetch your API, learn to manipulates it in a following blog :)