How to send a HTTP request from Google Cloud Functions (nodeJS)

The Request module uses callbacks. If you want to use JavaScript promises instead, the Axios module provides equivalent functionality.


Here is the code that I managed to get working with help from Chetan Kanjani. When I send a text message to my Google Cloud function endpoint, it replys with a text message to IFTTT (a different endpoint).

const request = require('request');

exports.helloWorld = function helloWorld(req, res) {
  // Example input: {"message": "Hello!"}
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);

    request.get('https://maker.ifttt.com/trigger/arrival/with/key/xxxx', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred 
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
      console.log('body:', body); //Prints the response of the request. 
    });
    res.status(200).send("Success");
  }
};

I also had to change the package.json file to include the request package. It already had the sample-http package, I added the dependencies:

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "request": "^2.81.0"
  }
}

I'm still not sure where the console.log function prints out the information. That might be helpful for future debugging.


The code below worked. Not sure if Axios is the ideal module for simple requests like these, but the Google Cloud Function documentation uses Axios so it seemed sensible to also use Axios. Other answers use the request module, but it was deprecated in February 2020.

Note: GCF doesn't support ES6 natively at this time. ES6 support is coming with Node 13.

Package.json

{
  "name": "YOUR_NAME",
  "version": "0.0.1",
  "dependencies": {
    "axios": "^0.19.2"
  }
}

Index.js

/**
 * Required Modules
 */
const axios = require("axios");


/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.run = async(req, res) => {
  // Set API end point.
  let apiURL = YOUR_URL;

  // Wrap API parameters in convenient object.
  let apiData = {
    PARAM_1: PARAM_DATA,
    PARAM_2: PARAM_DATA
  };

  // Invoke API.
  axios.post(apiURL,
    JSON.stringify(apiData)
  )
  .then((response) => {
    res.status(200).send(response.data);
    console.log(response);
  }, (error) => {
    res.status(500).send(response.data);
    console.log(error);
  });
};

Old, but I came across this while searching myself:

request module with promise support is (request-promise)