Back to home

SetupUsageReference
Web Fetch API main image

Web Fetch API

Full disclosure, I normally use axios as my library of choice for http fetching. This is in case I get asked this question in the upcoming interviews and they want me to use a native web API.

Setup

We are going to use Nodejs for this, so just create a file index.js anywhere you want.

The fetch API is promise based, so let's take a look as a basic implementation and then using async/await.

Because we are using node, we need to download the npm package that uses the same API. Let's setup the repo and package with the following:

1 yarn init -y | yarn add node-fetch

Usage

We will basically run the script as blocking, but syntax-wise we will run through both an await version and standard.

We will use https://postman-echo.com/post as our endpoint to essentially test if we make a successful call and look for the 200 status.

Standard

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 const fetch = require("node-fetch"); const runFetch = () => { const url = "https://postman-echo.com/post"; const json = { foo: "bar", }; return fetch(url, { method: "post", headers: { "Content-type": "application/json", }, body: JSON.stringify(json), }) .then(function (data) { console.log("Request succeeded with JSON response", data.status); }) .catch(function (error) { console.log("Request failed", error); }); }; const run = async () => await runFetch(); run();

If we run node index.js from our CLI we will see Request succeeded with JSON response 200.

Await

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 const fetch = require("node-fetch"); const runFetch = () => { return new Promise((resolve, reject) => { const url = "https://postman-echo.com/post"; const json = { foo: "bar", }; try { const data = fetch(url, { method: "post", headers: { "Content-type": "application/json", }, body: JSON.stringify(json), }); console.log("Request succeeded with JSON response", data.status); resolve(); } catch (err) { console.log("Request failed", error); reject(); } }); }; const run = async () => await runFetch(); run();

With this method, we are returning a Promise to begin with but manually running our try/catch block with a resolve/reject resolution based on failure or success.

Reference

  • https://developers.google.com/web/updates/2015/03/introduction-to-fetch

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.