Skip to content
background-image background-image

Using node-fetch (JSON API)

This example shows how to use node-fetch to communicate with JSON-based HTTP services.

Motivation

Suppose we have to process set of users and for each user we need to resolve his address by calling external HTTP-JSON service. Finally we need to submit users with addresses to another external service

Statement

// create array of users
const users = [
  {
    Login: "Alice",
  },
  {
    Login: "Bob",
  },
];

// or bind users from provided inputData if provided from previous step or endpoint
// const users = inputData;

// resolve addresses
const resolvingAddresses = users.map(async (u) => {
  // GET address for particular user
  const response = await fetch(`https://external.service/${u.Login}/resolve`);
  // read response
  const address = await response.json();
  return { ...u, ...address };
});

// wait for all requests
const usersWithAddress = await Promise.all(resolvingAddresses);

// submit users with addresses
// POST to https://external.service2 which requires authentication
const response = await fetch("https://external.service2/submit", {
  method: "post",
  body: JSON.stringify(usersWithAddresses),
  headers: {
    "Authentication": "Bearer secret",
    "Content-Type": "application/json",
    },
});

if (!response.ok) {
  throw new Error(`Failed to submit, service returned ${response.status}`);
}

return [];

Result

As you can see our step resolves user addresses and submits all users into another application.