Here, I'll be going over a simple fetch method to get the data from an API using javascript code.
I'll be using a public api called TVmaze, where you can get info on hundreds of tv shows! I love using this api to practice!
Let's start with fetch method. In your .js
file, add:
const url ='http://api.tvmaze.com/shows/1'
fetch (url)
.then(resp => resp.json())
.then(data => console.log(data)) //api data will be visible in your browser console.
.catch(err => console.warn("ERROR", err));
You will be able to see the data on your browser console, like this:
Now, to display a selected data on the browser, you need to create an id
or a class
in your .html
file.
<h1 id="name"></h1>
You are now able to grab the id
and add textContent
in your .js
file. In this case, I want the name of the tv show to display on the screen. I have created a function that executes this:
function info(data) {
document.getElementById("name").textContent = data.name;
}
Now, you need to call this function after you fetch the data:
fetch (url)
.then(resp => resp.json())
.then(info)
.catch(err => console.warn("ERROR", err));
Finally, data is displayed on the browser, like this:
And that's it! Thank you for making it till the end :)
Top comments (0)