banner

KuchBhiLearning - A free website to learn and code

This is a good learning site. This contains details of cloud computing, AWS, AWS-CDK, AWS-SDK codes and examples including S3, Redis, lambda, api-gateway, cloudfront, cloudformation.

Call external API from aws lambda using axios


Normally there are cases where we need to get some data from the database or in some cases we need to call the external API's. 

There are many ways to call the API's using the own helper methods, external packages.

In this example we will go through calling the external API's using the npm package.

There are many different methods and packages which does the job like 

  • HTTP
  • Node-Fetch
  • Axios
  • Express

In this example we will discuss about using the widely popular Axios package.

Installation is simple with below command

npm install axios

or if you are using yarn

$ yarn add axios

And the next is fairly simple, there are 2 ways to call the axios and both are working approach.

Create a ts file for example - 

hello.ts

import axios from 'axios;

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

or similarly we can call axios this way

// Send a POST request
axios({
  method: 'post',
  url: '/user/15',
  data: {
    firstName: 'test',
    lastName: 'lastname'
  }
});
// GET request for remote image in node.js
axios({
  method: 'get',
  url: 'https://bit.ly/2mabcdY',
  responseType: 'stream'
})
  .then(function (response) {
    console.log(response)
  });

No comments:

Post a Comment

If you have any doubts, Please let me know

Copyright 2022, KuchBhiLearning - A free website to learn and code. All rights Reserved.
| Designed by Yaseen Shariff