0
votes

I want to make a request from the Coinmarketcap API. They don't allow to use CORS configuration because security matters, the option is execute that in the browser by routing calls through an own backend service.

People said to me use several serverless options with free tier out there, AWS Lambda, Google Cloud Functions, Azure Functions. But I don't know how to do that, I'm wondering to use Aws Lambda, what I need to do?

That is my node.js code:



const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    'start': '1',
    'limit': '5000',
    'convert': 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' //that isn't my real api key
  },
  json: true,
  gzip: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response);
}).catch((err) => {
  console.log('API call error:', err.message);
});

1
So, what is the problem with the code you show that you want help with? - jfriend00

1 Answers

0
votes

The AWS Lambda function can help you to execute the api and return the response. You will also need probably AWS API Gateway to connect the response from lambda to your api. The code in lambda will look like this:

const rp = require('request-promise');

exports.handler = async (event) => {
  const requestOptions = {
    method: 'GET',
    uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
    qs: {
      'start': '1',
      'limit': '5000',
      'convert': 'USD'
    },
    headers: {
      'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' //that isn't my real api key
    },
    json: true,
    gzip: true
  };

  const response = rp(requestOptions);
  console.log(response);
  return response;
}

basically pass the input in event object and then you could use like a normal object. Also see - https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html