How to make API requests in Express

Last updated on Oct 9, 2022 by Suraj Sharma



In this tutorial, you'll learn how you can make API requests to external REST APIs in Express


To make API requests in the backend we will use the node-fetch npm module that works similar to window.fetch() function.


To get started, let's install the npm module


npm install --save node-fetch@2

Once the installation is complete. Import the node-fetch module in your existing Express project.


const fetch = require('node-fetch')


Make Get requests using node-fetch in Express


We will make a GET request to a REST API to test how we can fetch data from the API in Express


  const express = require('express');
  const cors = require('cors');
  const fetch = require('node-fetch');
  const app = express();

  const port = 3000;

  app.use(cors());

  app.get('/', async (req, res) => {
    try {
      response = await fetch('https://jsonplaceholder.typicode.com/users')
      const data = await response.json();
      res.send(data);
    } catch (error) {
      console.log(error);
      res.send({error: 'an error occurred'});
    }
  })

  app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
  });


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.