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
| API | URL | Data |
|---|---|---|
| JSONPlaceholder | jsonplaceholder.typicode.com | Users, posts, comments |
| OpenWeather | openweathermap.org/api | Weather (requires API key) |
| PokeAPI | pokeapi.co | Pokรฉmon |
| RandomUser | randomuser.me | Random 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
| Error | Cause | Solution |
|---|---|---|
fetch is not defined | Node.js < 18 | Update Node.js or use node-fetch |
ECONNREFUSED | API down | Check the URL |
SyntaxError: JSON | Response is not JSON | Check response.text() first |
Next step
โ Markdown Notes System โ Organize your knowledge