Google Apps Script – How to Trigger with HTTP POST

google-apps-script

I've been looking through all sorts of info about Script and haven't really found anything in regards to triggering a script with a HTTP POST. I'm looking to send one or two POST requests per hour to the script, have the script make a couple changes to the data in the requests, and then POST to somewhere else. The closest thing I found was running a script at set intervals (e.g. hourly) — I can modify what I'm trying to do to work with that, but it'd be easier if I could just POST to the script and be done with it.

Is this something Google Apps Script is capable of?

Best Answer

Yes, you can trigger an Apps Script function with an HTTPS POST request. You'll need to add a doPost() function to a script file. The doPost() function can also receive data from the POST request. If you want to receive data into the doPost() function, add a variable name inside of the parenthesis:

doPost(e) {
  // . . code here . . 

};

The documentation typically shows a variable named e inside of the parenthesis, but you can use any name that you want.

If you need to send a POST request from an Apps Script function, you can use:

UrlFetchApp.fetch()

The default type of request is a GET request, so you will need to use advanced options, and explicitly designate a POST request.

Google Apps Script Documentation - UrlFetchApp.fetch()

In order for the Apps Script project to be available, it must be published. In the script editor, click the "Publish" menu, and choose "Deploy as Web App". There are two versions of a Web App, the development version, and the "production" version. The development version has "dev" on the end of the URL. The production version has "exec" on the end of the URL.

The "exec" version of the Apps Script URL is what you must use for the URL in your POST request to your Apps Script project.

If you want to return something from the Apps Script web app, then you must use Content Service.

You can get more information from the following Stack Overflow post:

Call a custom GAS function from an external URL