Step: 1 What is an API?
Think of API as a postman who takes your letter to another person and gets back with a response.In simplest words, API is like a middle- man that helps client and server communicate with each other.
Step: 2 Call an AΡΙ
There are four steps to call an API:
1. Find an API
2. Request it
3. Handle response
4. Error handling
We will be using JavaScript to make the API call.
Step: 3
1. Find an API
We can use RapidAPI Hub, the home of over 35k+ APIs. I will use the Famous Quotes API from the Hub.
2.1 Request an API
We can use JavaScript fetch method to request an API.
// syntax
fetch('API_URL', {
// additional config
})
then(response => response.json())
then(data => console.log(data)) .catch(err => console.log(err));
2.2 Request an API
We will make a GET request to the API. Don't worry about the headers. You can find them on RapidAPI Hub.
// requesting famous quotes API using fetch
fetch('https://famous-quotes4.p.rapidapi.com/random?category=all&count=1', { method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com',
},
})
Step 4. Error handling
Lastly, let’s do some error handling in case the API request fails.
// requesting famous quotes API using fetch
fetch('https://famous-quotes4.p.rapidapi.com/random?category=all&count=1', { method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com',
},
})
then(response response.json())
.then(response console.log(response)) .catch(err console.error(err));
API Response
You will see a response like the following when you run your JavaScript file.
[
{
"text": "That neither our thoughts, nor passions, nor ideas formed by the imagination, exist without the mind, is what every body will allow.",
"author": "George Berkeley",
"id": 37917,
"category": "imagination"
}
]