Every earlier lesson in this course built a server that receives requests. This lesson is the other direction — a Node script or server calling another API, using the same fetch function already familiar from browser JavaScript.
Node 18 and later ships a global fetch — no package to install, no import needed.
const response = await fetch('https://api.example.com/users')
const users = await response.json()
console.log(users)Unlike most Node error handling, fetch does not throw for a 404 or 500 response — only for a genuine network failure. The status needs an explicit check.
const response = await fetch('https://api.example.com/users/999')
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`)
}
const user = await response.json()const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Sam', email: 'sam@example.com' }),
})
const created = await response.json()const response = await fetch('https://api.example.com/orders', {
headers: { Authorization: `Bearer ${apiToken}` },
})async function apiGet(path) {
const response = await fetch(`https://api.example.com${path}`, {
headers: { Authorization: `Bearer ${process.env.API_TOKEN}` },
})
if (!response.ok) {
throw new Error(`API error ${response.status}: ${await response.text()}`)
}
return response.json()
}
const orders = await apiGet('/orders')When a library still helps
Third-party libraries like axios still add real conveniences (automatic JSON parsing, request/response interceptors, built-in timeout handling) — worth reaching for on a larger project. Built-in fetch is enough for most everyday cases without adding a dependency.