How to Fetch API Data in Node.js – Step by Step Tutorial

Published by: Pankaj Chouhan | Codes With Pankaj

Introduction

Fetching data from an API is one of the most important skills for any backend or full-stack developer. In this easy tutorial, you will learn how to fetch data from a public API using Node.js and the built-in fetch() method.

This guide is perfect for beginners. No extra libraries are needed. We will use very simple and clean code with clear explanations.

Prerequisites

Before starting, make sure you have:

  • Node.js version 18 or higher installed
  • A code editor (VS Code is recommended)

Check Node.js version:

node --version

Step 1: Create a New Project

Open your terminal and run these commands:

mkdir node-fetch-api
cd node-fetch-api
npm init -y
Python

This will create a new folder and a package.json file.

Step 2: Create the Main File

Inside the node-fetch-api folder, create a new file named index.js.

Step 3: Write the Code

Copy and paste the following code into index.js:

// Simple Node.js Fetch API Example
// Codes With Pankaj - Beginner Friendly

const fetchAPIData = async () => {
  try {
    console.log(" Fetching data from API... Please wait...\n");

    // Free public test API
    const apiUrl = "https://jsonplaceholder.typicode.com/todos/1";

    // Step 1: Send request
    const response = await fetch(apiUrl);

    // Step 2: Check if request was successful
    if (!response.ok) {
      throw new Error(`HTTP Error! Status: ${response.status}`);
    }

    // Step 3: Convert response to JSON
    const data = await response.json();

    // Step 4: Display the result
    console.log("Data fetched successfully!\n");
    console.log(JSON.stringify(data, null, 2));

  } catch (error) {
    console.error("\n Error occurred:");
    console.error(error.message);
  }
};

// Run the function
fetchAPIData();
Python

Step 4: Run the Program

In the terminal, run this command

node index.js

Expected Output:

Fetching data from API... Please wait...

Data fetched successfully!

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

How the Code Works

Code PartWhat It Does
async () =>Allows us to use await (because API calls take time)
await fetch(apiUrl)Sends request to the API and waits for response
response.okChecks if the request was successful
response.json()Converts the data into a JavaScript object
try...catchHandles errors safely
JSON.stringifyFormats the data nicely for printing

Real-life Example:
Fetching API data is like ordering food from a restaurant app. You place the order (fetch), wait for it (await), and then open the package (response.json()).

Practice Tasks for You

  1. Change the URL to fetch a blog post:
   const apiUrl = "https://jsonplaceholder.typicode.com/posts/5";
  1. Fetch all todos (returns an array):
   const apiUrl = "https://jsonplaceholder.typicode.com/todos";
  1. Try a wrong URL to see error handling in action.

Fetch List from API and Display in HTML Table

Step 1: Create New Project

mkdir node-fetch-table
cd node-fetch-table
npm init -y

Step 2: Install Express (for web server)

npm install express

Step 3: Create Project Files

Create these two files in your project folder:

  1. index.js (Main server file)
  2. public/index.html (HTML file with table)

File 1: index.js

// =============================================
// Fetch API List & Show in HTML Table - Node.js
// Codes With Pankaj
// =============================================

const express = require('express');
const app = express();
const port = 3000;

// Serve static files (HTML, CSS, JS)
app.use(express.static('public'));

// Route to fetch data and send to frontend
app.get('/api/todos', async (req, res) => {
  try {
    const apiUrl = "https://jsonplaceholder.typicode.com/todos";

    const response = await fetch(apiUrl);

    if (!response.ok) {
      throw new Error('Failed to fetch data');
    }

    const todos = await response.json();

    // Send data as JSON to frontend
    res.json(todos);

  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Something went wrong!" });
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
  console.log(`Open your browser and visit: http://localhost:${port}`);
});

File 2: Create Folder public and file public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Todo List - Codes With Pankaj</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
      background: #f4f4f4;
    }
    h1 {
      color: #333;
      text-align: center;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;
      background: white;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    th, td {
      padding: 12px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }
    th {
      background-color: #4CAF50;
      color: white;
    }
    tr:hover {
      background-color: #f1f1f1;
    }
    .completed {
      color: green;
      font-weight: bold;
    }
    .loading {
      text-align: center;
      font-size: 18px;
      color: #666;
    }
  </style>
</head>
<body>
  <h1>📋 Todo List from API</h1>
  <p style="text-align:center;">Fetched using Node.js + Express</p>

  <div class="loading" id="loading">Loading data... Please wait...</div>

  <table id="todoTable" style="display: none;">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>

  <script>
    async function fetchAndDisplayTodos() {
      try {
        const response = await fetch('/api/todos');
        const todos = await response.json();

        const tbody = document.querySelector('#todoTable tbody');
        tbody.innerHTML = '';

        todos.forEach(todo => {
          const row = document.createElement('tr');
          row.innerHTML = `
            <td>${todo.id}</td>
            <td>${todo.title}</td>
            <td class="${todo.completed ? 'completed' : ''}">
              ${todo.completed ? 'Completed' : '⏳ Pending'}
            </td>
          `;
          tbody.appendChild(row);
        });

        // Hide loading and show table
        document.getElementById('loading').style.display = 'none';
        document.getElementById('todoTable').style.display = 'table';

      } catch (error) {
        console.error(error);
        document.getElementById('loading').innerHTML = 
          '<p style="color:red;">Failed to load data. Please check your server.</p>';
      }
    }

    // Load data when page opens
    window.onload = fetchAndDisplayTodos;
  </script>
</body>
</html>

Step 4: Run the Project

node index.js

Then open your browser and go to:
http://localhost:3000

You will see a beautiful table with 200 todos fetched from the API!

Features of This Example

  • Fetches full list from API in Node.js
  • Displays data in clean HTML table
  • Shows loading message
  • Color-coded status (Completed / Pending)
  • Hover effect on rows
  • Error handling

Important Tips

  • Always use try...catch when working with APIs.
  • For older Node.js versions (<18), you may need to install node-fetch package.
  • In real projects, many developers use the Axios library for more features.
  • Always check response.ok before reading the data.

Conclusion

Congratulations! You have successfully learned how to fetch API data in Node.js.

This is a fundamental skill used in almost every modern web application. Practice this example daily and try fetching data from different free APIs.

What’s Next?

  • Learn how to make POST requests
  • Use Axios library
  • Build a full REST API with Express.js
  • Would you like me to write the next tutorial? Just tell me!
Scroll to Top