Posts Learn Components Snippets Categories Tags 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

14 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: '...' /* ... */ },
];

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More