HomeNode JSHow to call Third-party API in Node.Js

How to call Third-party API in Node.Js

- Advertisement -spot_img

In today’s web development landscape, integrating third-party APIs is a common and essential task. Whether you’re consuming data from external services, sending requests to interact with a remote server, or integrating with other platforms, Node.js is a powerful and efficient choice for making HTTP requests.

In this blog post, we’ll walk through how to call a third-party API in Node.js using different methods, including using built-in modules as well as third-party libraries. Lets start how to call third-party APIs call in Node Js


How to Call a Third-Party API in Node.js

What You’ll Need:

  1. Node.js installed – If you haven’t installed Node.js yet, you can download it from the official website.
  2. A third-party API to work with – For demonstration purposes, we’ll use the JSONPlaceholder API, a free fake online REST API used for testing and prototyping.

Method 1: Using the Built-in http Module

Node.js provides an http module that allows you to make HTTP requests. While this works well, it’s not the most convenient option for more complex interactions.

Let’s see how to make a simple GET request to an external API using the http module:

const http = require('http');

// Define the URL of the API
const url = 'http://jsonplaceholder.typicode.com/posts/1';

http.get(url, (res) => {
  let data = '';

  // A chunk of data has been received.
  res.on('data', (chunk) => {
    data += chunk;
  });

  // The response has been fully received.
  res.on('end', () => {
    console.log('Response Data:', JSON.parse(data));
  });

}).on('error', (err) => {
  console.log('Error:', err.message);
});

Breakdown:

  • We require the http module and use the http.get() method to send a GET request to the API.
  • The data event is fired when a chunk of data is received, and we accumulate it in a variable.
  • The end event indicates that the entire response has been received, at which point we log the parsed JSON response.

Limitations: This approach is quite basic and doesn’t handle things like request headers, query parameters, or more complex API interactions as easily.


Method 2: Using the axios Library

axios is a popular third-party library that simplifies making HTTP requests. It provides a rich set of features such as handling request and response transformations, promise-based syntax, and automatic JSON parsing.

  1. Installation:

First, install axios using npm:

npm install axios
  1. Making a GET Request with axios:
const axios = require('axios');

// Define the API endpoint
const url = 'http://jsonplaceholder.typicode.com/posts/1';

axios.get(url)
  .then(response => {
    console.log('Response Data:', response.data);
  })
  .catch(error => {
    console.log('Error:', error.message);
  });

Breakdown:

  • axios.get(url) makes the GET request to the specified URL.
  • The .then() method handles the successful response, and we can directly access the response.data which contains the parsed JSON.
  • The .catch() method catches any errors that occur during the request.

Benefits of axios:

  • Supports both Promise and async/await syntax.
  • Automatically parses JSON responses.
  • Handles request and response interceptors, which can be useful for things like authentication tokens or logging.

Method 3: Using the node-fetch Library

node-fetch is another lightweight library for making HTTP requests, similar to fetch in the browser. It’s often preferred when working with async/await syntax, as it’s more intuitive and modern.

  1. Installation:

Install node-fetch using npm:

npm install node-fetch
  1. Making a GET Request with node-fetch:
const fetch = require('node-fetch');

// Define the API endpoint
const url = 'http://jsonplaceholder.typicode.com/posts/1';

(async () => {
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log('Response Data:', data);
  } catch (error) {
    console.log('Error:', error.message);
  }
})();

Breakdown:

  • We use fetch() to send the request, which returns a Promise.
  • The await keyword ensures that the code waits for the response.
  • The response.json() method is used to parse the JSON response body.

Benefits of node-fetch:

  • Simple and minimalistic API.
  • Works seamlessly with async/await for better readability and flow.
  • Ideal for use with REST APIs that return JSON.

Method 4: Using the request (Deprecated but Still in Use) Library

While the request library has been deprecated, it is still widely used in older Node.js projects. It offers a simple and flexible interface to make HTTP requests.

  1. Installation:

To install request:

npm install request
  1. Making a GET Request with request:
const request = require('request');

// Define the API endpoint
const url = 'http://jsonplaceholder.typicode.com/posts/1';

request(url, (error, response, body) => {
  if (error) {
    console.log('Error:', error.message);
  } else if (response.statusCode === 200) {
    console.log('Response Data:', JSON.parse(body));
  } else {
    console.log('Failed with status code:', response.statusCode);
  }
});

Breakdown:

  • The request() method sends the HTTP request.
  • The callback function receives the error, response, and body parameters.
  • If the response is successful (status code 200), the response body is parsed as JSON.

Note: While request is still popular, it is no longer actively maintained. It’s advisable to use alternatives like axios or node-fetch for new projects.


Handling POST Requests

For making POST requests, most of these libraries (like axios and node-fetch) support sending data along with the request. Here’s an example using axios:

const axios = require('axios');

const url = 'http://jsonplaceholder.typicode.com/posts';

const postData = {
  title: 'foo',
  body: 'bar',
  userId: 1
};

axios.post(url, postData)
  .then(response => {
    console.log('Response Data:', response.data);
  })
  .catch(error => {
    console.log('Error:', error.message);
  });

In this example, axios.post() sends a POST request with data (postData) in the request body.


Conclusion

Calling third-party APIs in Node.js is straightforward, thanks to built-in modules like http, and external libraries like axios and node-fetch. Depending on your project needs, you can choose the most appropriate method.

  • For simplicity: Use axios or node-fetch, as they offer cleaner syntax, better error handling, and easy integration with modern JavaScript features like async/await.
  • For legacy projects: If you’re working with older codebases, you might encounter request, though it’s advisable to move away from it since it’s now deprecated.

By integrating third-party APIs effectively, you can extend the functionality of your Node.js applications and leverage external data and services seamlessly.

Stay Connected
16,985FansLike
2,458FollowersFollow
61,453SubscribersSubscribe
Must Read
Related News

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here