Posts Learn Components Snippets Categories Tags Tools new About
/

Getting a Resource with Fetch API in JavaScript

Learn how to get or request a resource using fetch API in JavaScript the easy and native way.

Created on Aug 27, 2021

26 views

In this short snippet, you will learn how to use "fetch" method to retrieve API in JavaScript. For this example, we will be using "{JSON} Placeholder" which is a "Free fake API for testing and prototyping".

Fake API Source


Do visit the website to get more info on the available resources to request.
http://jsonplaceholder.typicode.com/

JavaScript Fetch Example


To easily fetch a resource from an external API in JavaScript you can use "fetch" method like below. In this example, it's fetching a post from a fake API and upon getting the result it's parsed into JSON and then finally logged into the console after passing it again from the JavaScript promise.
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((response) => response.json())
  .then((json) => console.log(json));

Output


Now when you look at the "console.log", the output of the response will have 100 objects like below.
[
  { id: 1, title: '...' /* ... */ },
  { id: 2, title: '...' /* ... */ },
  { id: 3, title: '...' /* ... */ },
  /* ... */
  { id: 100, title: '...' /* ... */ },
];

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)