DEV Community

Cover image for Short API GET using HTML, JS and Axios
Andre Paiva
Andre Paiva

Posted on

Short API GET using HTML, JS and Axios

Hello there!

I'd like to share the shortest way I found to make an API GET request and render on navigator using just HTML, JavaScript and Axios. This can be useful for beginners to test and understand how async and await works on API callings. And also give the first steps with Axios.

I tried to keep the fewest amount of code as possible. Please feel free to post your comment so I can fix or include something making this post more interesting, ok? ;)

First, create an index.html file with this content:

An image of the HTML code

  • In the first script tag it was imported the Axios library, so we can use their functions.
  • On the tag with the id data we will embed the data from API.
  • The second script tag will call the second file below, which will provide the data to the page.

This is script.js file:

An image of the JavaScript code

How it works is simple:

The function getAllTitles creates a constant with the object containing the Axios configuration related to the request we are creating.

As you can see, getAllTitles is an async type of function, which means that, when the code interpreter hits the await word, it will stop until the value arrives from the promise. This will ensure that getAllTitles will return the data (or an error, but errors exceptions are not the focus of this article).

The renderResult function is an asynchronous function too, because it needs the value returned from getAllTitles to change the DOM, rendering the API content.

Result:

Now, just run your project and see the data on your navigator.

The screenshot with the results from the API

Hope you like these tips! Try changing the code and get different data from the API by consoling res.data.

Any questions just leave your comment, we have a great community willing to help!

Discussion (2)

Collapse
gorlok profile image
gorlok 🧉 • Edited on

Why using Axios when you can use JS's fetch()? Short API GET? Use JS - It's even simpler and without any dependencies.

fetch('api.publicapis.org/entries')
.then(resp => resp.json())
.then(data => data.entries.map((e) => {
let p = document.createElement('p')
let a = document.createElement('a')
p.appendChild(a);
a.setAttribute('href', e.Link)
a.innerHTML = e.API
document.getElementById('data').appendChild(p)
}))

Collapse
afpaiva profile image
Andre Paiva Author

Yes, you are right! It is really shorten.
But the idea of this post is to use Axios as short as I could. So that beginners in Axios, like me), can see how to start using it understanding the minimum usage of it. Like an entry point for study.
Great point, thanks for your comment!