Home / Snippets / Getting a Resource with Fetch API in JavaScript
Getting a Resource with Fetch API in JavaScript cover

Getting a Resource with Fetch API in JavaScript

131

3 years ago

0 comments

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this