How to call an API in Javascript: Random Meal Generator
Since the beginning of 2021, I've been taking part in Scrimba 's #WeeklyWebDevChallenge. For Week 5, the challenge was to create an application that implemented the Foodish API ๐.
I decided to create a Random Meal Generator that calls the API to show a different meal along with a relevant image. To push myself, I tried to implement 3 Different Ways to call an API:
- XMLHttpRequest
- Fetch
- Axios
You can checkout my application here โจ and the steps of how I did each method below :)
Method 1 - XMLHttpRequest
1. Create a XMLHttpRequest
object
XMLHttpRequest
is an object that allows us to make HTTP requests in JavaScript. When you create a XMLHttpRequest
object, this is just a constructor and has no arguments.
2. Initialise the object using .open()
Once the XMLHttpRequest
object has been constructed, it needs to be initialised. When this happens, the HTTP-method and URL are passed as parameters to configure the request.
3. Send the request
In order to actually send the request, we can use the aptly named method .send()
. This will open a connection and send the request to the server.
4. Handle the response
After the request has been sent, there needs to be a method to listen out for when the request has completed. This can be done with the method onload
, where the response data can be accessed and used.
In the example snippet below, I check that request.status === 200
, as that indicates the request was a success. Within that, I grab the image and name to display on the page. Otherwise, I log a message to the console letting me know there was an error.
// Method 1 - XMLHttpRequest
function getRandomMeal() {
var randomMeal = meals[Math.floor(Math.random() * meals.length)];
// Step 1
const request = new XMLHttpRequest();
// Step 2
request.open("GET", "https://foodish-api.herokuapp.com/api/images/" + randomMeal);
// Step 3
request.send();
// Step 4
request.onload = () => {
if (request.status === 200) {
let response = JSON.parse(request.response);
name.innerHTML = randomMeal.charAt(0).toUpperCase() + randomMeal.slice(1);
image.src = response.image;
imageContainer.style.display = 'block';
} else {
console.log("Error", request);
}
}
}
Method 2 - Fetch
1. Make the request using fetch()
fetch()
allows us to send requests and get information from a server by taking the URL as a parameter. It works in a two stage process that uses promises.
2. Handle the promise
When using fetch()
, it returns a promise. The promise is rejected if the fetch()
was unable to make the request. However, if not, we can use .then()
to return the response from that.
3. Handle the response
In a similar fashion, after the response had been returned, we can use another .then()
to do what we need with the response data.
// Method 2 - Fetch
function getRandomMeal() {
var randomMeal = meals[Math.floor(Math.random() * meals.length)];
// Step 1
fetch("https://foodish-api.herokuapp.com/api/images/" + randomMeal)
// Step 2
.then((response) => {
return response.json();
})
// Step 3
.then((meal) => {
name.innerHTML = randomMeal.charAt(0).toUpperCase() + randomMeal.slice(1);
image.src = meal.image;
imageContainer.style.display = 'block';
});
}
Method 3 - Axios
1. Include Axios in your application
There are several ways to do this, but I think the easiest way to include Axios is by using an external CDN. I have included mine in a script tag in my HTML file.
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
2. Make the request using axios.get()
Very similar to fetch()
, we can use axios.get()
to send requests by taking the URL as a parameter.
3. Handle the response
axios.get()
returns a response when the request is completed. This can be accessed using .then()
, where the response data can be used as necessary.
// Method 3 - Axios
function getRandomMeal() {
var randomMeal = meals[Math.floor(Math.random() * meals.length)];
// Step 2
axios.get("https://foodish-api.herokuapp.com/api/images/" + randomMeal)
// Step 3
.then((response) => {
name.innerHTML = randomMeal.charAt(0).toUpperCase() + randomMeal.slice(1);
image.src = response.data.image;
imageContainer.style.display = 'block';
})
.catch((error) => {
console.log("Error", error);
});
}
I'm not an expert on this by any means, but I just wanted to share what I learned. If you have any thoughts or comments on how I can improve, please do let me know! โจ