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

Viewed 28628

This is probably a simple question but I'm new to cloud functions/Node programming and haven't found the right documentation yet.

How do I write a Google cloud function that will receive a HTTP request but then send a HTTP request to a different endpoint? For example, I can send the HTTP trigger to my cloud function (https://us-central1-plugin-check-xxxx.cloudfunctions.net/HelloWorldTest). Later in the project I'll figure out how to implement a delay. But then I want to respond with a new HTTP request to a different endpoint (https://maker.ifttt.com/trigger/arrive/with/key/xxxx). How do I do that?

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);
    res.status(200).send('Success: ' + req.body.message);
    // ??? send a HTTP request to IFTTT endpoint here
  }
};
5 Answers

Old, but I came across this while searching myself:

request module with promise support is (request-promise)

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);
  });
};
Related