Here is a course that shows how to make a simple API calls with the fetch() method in Javascript
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
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 :)