๐Ÿ”—

Consume a JSON API

๐Ÿง‘โ€๐ŸŽ“ Apprenticeโฑ๏ธ 15 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขNode.js installed

What you'll build

In this project you'll learn how to fetch data from the internet using APIs.

You'll create a script that connects to a public API, downloads user information, and displays it formatted in your terminal. This is the foundation of any modern application: getting external data and processing it.

When finished, you'll understand how REST APIs work and be able to connect to any service that offers one.


Step 1: A free public API

We'll use JSONPlaceholder, a test API.

# Test from terminal
curl https://jsonplaceholder.typicode.com/users/1

Step 2: Ask an AI for the code

I need a Node.js script that:
- Fetches https://jsonplaceholder.typicode.com/users
- Shows the name and email of each user
- Uses async/await

Step 3: Typical code

The AI will give you something like:

async function getUsers() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const users = await response.json();

  users.forEach(user => {
    console.log(`${user.name} - ${user.email}`);
  });
}

getUsers();

Step 4: Run it

node fetch-users.js

You'll see a list of users with their emails.


Other public APIs

APIURLData
JSONPlaceholderjsonplaceholder.typicode.comUsers, posts, comments
OpenWeatheropenweathermap.org/apiWeather (requires API key)
PokeAPIpokeapi.coPokรฉmon
RandomUserrandomuser.meRandom users

Error handling

async function getUsers() {
  try {
    const response = await fetch('https://api.example.com/users');

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

If something failed

ErrorCauseSolution
fetch is not definedNode.js < 18Update Node.js or use node-fetch
ECONNREFUSEDAPI downCheck the URL
SyntaxError: JSONResponse is not JSONCheck response.text() first

Next step

โ†’ Markdown Notes System โ€” Organize your knowledge