Integrating External APIs: Using Fetch and Axios in Node.js
Learn how to perform API integration by making outgoing HTTP requests in Node.js. Master Fetch and Axios to fetch data and handle external API responses.
Previously in this course, we covered monitoring deployed APIs, ensuring our own services are healthy and visible. Now that your server is running, you'll often need it to talk to other services—like fetching weather data, processing payments, or pulling user profiles from a third party.
This lesson focuses on API integration, teaching you how to make your Node.js server act as a client that consumes data from external providers.
Choosing an HTTP Client: Fetch vs. Axios
To make requests, you need an HTTP client. While there are many options, two stand out for modern Node.js development:
- Fetch API: Built directly into Node.js (v18+). It’s lightweight, native, and requires no dependencies.
- Axios: A popular third-party library that offers a more feature-rich API, automatic JSON transformation, and better request cancellation support.
| Feature | Fetch | Axios |
|---|---|---|
| Dependency | Built-in | Requires npm install axios |
| JSON Parsing | Manual (.json()) | Automatic |
| Interceptors | No (native) | Yes |
| Timeout Support | Requires AbortController | Built-in |
Making External API Calls with Fetch
Since Node.js v18, fetch is globally available. If you are on an older version, you'll need to upgrade or install a polyfill, but for this course, we'll assume a modern environment.
Here is how to fetch data from a public API:
JAVASCRIPT// Using Fetch to get data async function getUserData(userId) { try { const response = await fetch(CE9178">`https://jsonplaceholder.typicode.com/users/${userId}`); // Fetch doesn't throw errors on 404/500, so we check ok status if (!response.ok) { throw new Error(CE9178">`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log(data); } catch (error) { console.error("Failed to fetch user:", error.message); } }
Simplifying Requests with Axios
If your application requires complex headers, automated retries, or frequent POST requests with JSON bodies, Axios is often preferred for its clean syntax.
First, install the package:
npm install axios
Then, implement the call:
JAVASCRIPTconst axios = require(CE9178">'axios'); async function createUser(userData) { try { // Axios automatically stringifies the body and sets content-type const response = await axios.post(CE9178">'https://jsonplaceholder.typicode.com/users', userData); return response.data; } catch (error) { // Axios throws an error for any status code outside of 2xx console.error("Error creating user:", error.response?.data || error.message); } }
Hands-on Exercise: Fetching Data in Your App
In your existing project, create a new route in your routes/external.js file that fetches a random quote or user data from a public API when the endpoint is hit.
- Install Axios:
npm install axios. - Create a route
GET /api/external-data. - Use
axiosto fetch data fromhttps://jsonplaceholder.typicode.com/todos/1. - Return the fetched title to your client using
res.json(). - Ensure you wrap your logic in a
try/catchblock to handle potential network failures.
Common Pitfalls to Avoid
- Forgetting
await: Bothfetchandaxiosreturn Promises. Forgetting to await them will leave you with a Promise object instead of the actual data. - Assuming 200 OK: The native
fetchAPI only rejects the promise if there is a network error. If the server returns a404or500,fetchconsiders that a "success." Always checkresponse.ok. - Hardcoding URLs: Never hardcode API keys or base URLs. Use environment variables (which we covered in mastering environment variables in Node.js with dotenv) to manage configuration.
- Unsafe Error Handling: Never expose raw external error messages to your own API users, as they may contain sensitive server information.
FAQ
Q: Why does my Fetch call fail with a 404 but not trigger the catch block?
A: fetch only throws an error for network-level failures (DNS, connection timeout). You must explicitly check if (!response.ok) to handle HTTP error status codes.
Q: Should I use Axios or Fetch?
A: For simple scripts or modern Node.js apps, fetch is great. If you are building a large-scale project that needs interceptors, global defaults, or consistent error handling, axios is the industry standard.
Q: How do I send headers with my requests?
A: With axios, pass an object as the third argument: axios.get(url, { headers: { 'Authorization': 'Bearer token' } }).
Recap
We’ve learned that external API integration allows our server to communicate with the outside world. We explored the native Fetch API for zero-dependency requests and Axios for more robust, feature-heavy scenarios. Remember to always validate your responses and handle errors gracefully to keep your service stable.
Up next: Asynchronous Patterns (Promises), where we learn to handle multiple API calls efficiently without blocking the event loop.
Work with me

Laravel REST API Development
Clean, secure, well-documented Laravel REST APIs — the backend engine for your app, mobile client, or SaaS. Built by an API specialist.

Next.js Full-Stack Web App Development
A fast, SEO-ready full-stack web app built with Next.js 16 — from idea to deployed product, by an engineer who ships to production.


