Using Fetch in Javascript to get data from an API


Published on 06 May 2022


Using Fetch in Javascript to get data from an API

Fetch in Javascript

Javascript has its own way of getting data from an API, it is by writing "fetch(url)", where URL is the url of the API, which can be received as a JSON file or in any other way.
This fetch() method can be used as a promise method and can be accompanied by "THEN()" and "CATCH"().
With the fetch() method a promise is obtained, if the returned promise is resolve, the function inside the then() method is executed. That function contains the code to handle the data received from the API.

fetch(url).then(function(){}).catch(function(){});

Example:

<script type="text/javascript">
fetch('/example.json')
 .then((response) => response.json())
 .then((data) => {
  console.log(data);
 });

</script>

Note that fetch always makes http requests so it is not useful for local variables.
In the following example we show how you can collect data from the API through JSON and create html elements and insert this data:

<script type="text/javascript">
fetch('/example.json')
 .then((response) => response.json())
 .then((user) => fetch(`https://api.example.com/users`))
 .then((response) => response.json())
 .then((exampleUser) => {
  let img = document.createElement('img')
  img.src = exampleUser.imgUrl
  document.body.append(img)
 })
 .catch(error => console.error(error.message));
</script>

Previous Chapter - Next Chapter


Tips on SEO and Online Business

Next Articles

Previous Articles