Consuming Third-party APIs
Talk to services you did not build - and survive it when they misbehave
- call a JSON API from Node with the built-in
fetch, - send authentication headers (Bearer tokens and API keys) safely,
- recognise and respect rate limits (HTTP 429 and
Retry-After), - build resilient calls with timeouts, retries and exponential backoff,
- decide when
axiosearns its place overfetch.
1. What "consuming an API" really means
A third-party API is an HTTP service owned by someone else. You are the client: you send a request, they send back a response - usually JSON. Your Node program becomes a consumer of their data or actions.
Analogy. Calling an API is like ordering at a restaurant. You (the client) read the menu (the docs), place an order in the exact format the kitchen expects (the request), and show your membership card if the place is members-only (the auth header). The kitchen may be slammed and ask you to wait (rate limiting), or a dish may be unavailable (an error status). A careful diner plans for all of that instead of assuming every order arrives instantly and perfectly.
Since Node 18, a browser-style fetch function is built in - no package needed. It returns a Promise, so you use it with async/await, exactly the skills you already have:
// Node 18+ : fetch is global, no import needed
const res = await fetch('https://api.github.com/users/nodejs');
const data = await res.json();
console.log(data.name, data.public_repos);
Two awaits, two stages: fetch(...) resolves once the headers arrive, and res.json() resolves once the whole body has been read and parsed. Keep those two stages separate in your mind - a lot of bugs hide in the gap between them.