Back to Blog
Lesson 42 of the Node.js: Build Your First Server & CLI course
Node.jsAugust 30, 20264 min read

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.

Node.jsAPI integrationAxiosFetchHTTP clientWeb Development

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:

  1. Fetch API: Built directly into Node.js (v18+). It’s lightweight, native, and requires no dependencies.
  2. Axios: A popular third-party library that offers a more feature-rich API, automatic JSON transformation, and better request cancellation support.
FeatureFetchAxios
DependencyBuilt-inRequires npm install axios
JSON ParsingManual (.json())Automatic
InterceptorsNo (native)Yes
Timeout SupportRequires AbortControllerBuilt-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:

JAVASCRIPT
const 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.

  1. Install Axios: npm install axios.
  2. Create a route GET /api/external-data.
  3. Use axios to fetch data from https://jsonplaceholder.typicode.com/todos/1.
  4. Return the fetched title to your client using res.json().
  5. Ensure you wrap your logic in a try/catch block to handle potential network failures.

Common Pitfalls to Avoid

  • Forgetting await: Both fetch and axios return Promises. Forgetting to await them will leave you with a Promise object instead of the actual data.
  • Assuming 200 OK: The native fetch API only rejects the promise if there is a network error. If the server returns a 404 or 500, fetch considers that a "success." Always check response.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.

Similar Posts