What is an API Call?

What is an API?

An Application Program Interface (API) acts as a source of communication between software programs. With the help of an API, a developer doesn't have to write the code from scratch. They can simply use an existing API that will save time and resources. Using an API also helps with software integration, which in turn improves the user experience. After developing an API, we make an API call to request resources from the server and perform other operations.

What is an API call?

An API call is a procedure by which information is exchanged. The client sends a request to an API. The API sends the request to the server and gets the response back to the client via that same API.

How an API call works

HTTP methods to make an API call

To communicate with our API, we use the following requests methods:

  • GET: This requests data from a resource. This method only retrieves data.

  • POST: This method creates new resources on the server. It accepts a request body. The API then takes that request body to the server to perform the create operation in the database.

  • PUT: This method modifies a record by replacing the existing one with the updated one.

  • HEAD: This requests data from a resource without retrieving it. We usually use this method before GET.

  • DELETE: This deletes a record from the database.

  • PATCH: This partially updates a resource.

  • CONNECT: This creates a connection with the resource.

  • TRACE: This carries out a message loop-back test.

  • OPTIONS: This method tells us the communication options available for that resource.

How to make an API call

We use the GET method to call an API in Node.js.

Step 1: Install Node.js

Install Node.js from here.

Step 2: Create a directory and open it in a code editor

We then create a directory on our computer and open it in a code editor like VIM, sublime text, VS code, and so on.

Step 3: Set up a Node.js project

This command is going to initialize the Node.js project in the directory. The -y flag will use all the default values.

npm init -y

Step 4: Install Axios

Axios is an npm package that lets us call an API in our Node.js project. After this, we create an index.js file.

npm install axios

Step 5: Use a GET request to call an API

Here's how we make the GET request:

// Importing libraries here
const fetch = require("node-fetch");
// Define endpoint URL here
// const endpointUrl = "https://api.sandbox.transferwise.tech/v1/rates";
const endpointUrl = 'https://jsonplaceholder.typicode.com/posts';
// Define Header Parameters here
const headerParameters = {
// authorization: API_KEY,
"Content-Type": "application/json",
};
// Setting API call options
const options = {
method: "get",
headers: headerParameters,
};
// Function to make API call
async function fetchSomethingJSON() {
try {
const response = await fetch(endpointUrl, options);
// Printing response
printResponse(response);
} catch (error) {
// Printing error message
printError(response);
}
}
// Calling function to make API call
fetchSomethingJSON();
const axios = require('axios');
(async () => {
const makeGETRequest = async url => {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log(error);
}
};
const response = await makeGETRequest
('https://jsonplaceholder.typicode.com/posts');
console.log(response);
})();

Code explanation

  • Line 1: We import Axios.

  • Lines 3–4: We create an immediately invoke function expression (IIFE)A JavaScript function that runs as soon as it is defined.. This is because we have to await a function that we use later in the code. To do that, we wrap it in an async function. Moreover, when our file executes, this function will automatically be executed. We won't have to call it specifically. We then make a makeGETRequest function that is asynchronous.

  • Lines 5–11: We make an HTTP GET request to an external API that will return a list of posts. To make the GET request, we use axios.get(url). We put our request in a try and catch block to deal with errors. We used the await keyword to ensure the data was received.

  • Lines 13–16: We call our makeGETRequest function by putting the URL of the external API.

Step 6: Run your code

Run your code by using the following command:

node index.js

We can use the other HTTP methods in the same way. The only thing we need to change would be replacing get with the method's name. For example, if we want to send a POST request, we would use axios.post(url) instead of axios.get(url).

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved