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.
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.
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.
We use the GET
method to call an API in Node.js
.
Install Node.js from here.
We then create a directory on our computer and open it in a code editor like VIM, sublime text, VS code, and so on.
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
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
GET
request to call an APIHere's how we make the GET
request:
// Importing libraries hereconst 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 hereconst headerParameters = {// authorization: API_KEY,"Content-Type": "application/json",};// Setting API call optionsconst options = {method: "get",headers: headerParameters,};// Function to make API callasync function fetchSomethingJSON() {try {const response = await fetch(endpointUrl, options);// Printing responseprintResponse(response);} catch (error) {// Printing error messageprintError(response);}}// Calling function to make API callfetchSomethingJSON();
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);})();
Line 1: We import Axios.
Lines 3–4: We create an 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.
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