Sample Scripts for Requesting to Web Apps by Various Languages

Gists

These are the sample scripts by the various languages for requesting to Web Apps created by Google Apps Script.

  1. curl
  2. Google Apps Script
  3. Javascript
  4. ajax
  5. Node.js
  6. axios
  7. angular
  8. go
  9. python
  10. php
  11. powershell

Sample script for Web Apps

  • Sample script for Web Apps is as follows.

    const doGet = (e) =>
      ContentService.createTextOutput(
        JSON.stringify({ method: "GET", eventObject: e })
      ).setMimeType(ContentService.MimeType.JSON);
    const doPost = (e) =>
      ContentService.createTextOutput(
        JSON.stringify({ method: "POST", eventObject: e })
      ).setMimeType(ContentService.MimeType.JSON);
    
  • Setting for Web Apps is as follows.

    • Execute the app as: Me
    • Who has access to the app: Anyone, even anonymous
    • In this settings, no access token is required. When you use other settings, it might be required to use the access token. About this, please check here.

1. curl

To doGet

$ curl -L "https://script.google.com/macros/s/#####/exec?key1=value1&key2=value2&key3=value3"

Result

{
  "method": "GET",
  "eventObject": {
    "contentLength": -1,
    "parameters": {
      "key2": ["value2"],
      "key1": ["value1"],
      "key3": ["value3"]
    },
    "contextPath": "",
    "parameter": {
      "key1": "value1",
      "key3": "value3",
      "key2": "value2"
    },
    "queryString": "key1=value1&key2=value2&key3=value3"
  }
}

To doPost

$ curl -L -H "application/json" -d '{"key1": "value1", "key2": "value2"}' "https://script.google.com/macros/s/#####/exec?key3=value3"

Result

{
  "method": "POST",
  "eventObject": {
    "contextPath": "",
    "postData": {
      "contents": "{\"key1\": \"value1\", \"key2\": \"value2\"}",
      "length": 36,
      "name": "postData",
      "type": "application/x-www-form-urlencoded"
    },
    "parameters": {
      "key3": ["value3"],
      "{\"key1\": \"value1\", \"key2\": \"value2\"}": [""]
    },
    "contentLength": 36,
    "queryString": "key3=value3",
    "parameter": {
      "{\"key1\": \"value1\", \"key2\": \"value2\"}": "",
      "key3": "value3"
    }
  }
}
  • When you don’t want to show "{\"key1\": \"value1\", \"key2\": \"value2\"}": [""] and {\"key1\": \"value1\", \"key2\": \"value2\"}": "", please include the content type of application/json. But when this content type is added, there is the case that an error occurs by the language. So please be careful this.

2. Google Apps Script

To doGet

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key1=value1&key2=value2&key3=value3`;
const res = UrlFetchApp.fetch(url);
console.log(res.getContentText());

Result

Same as above.

To doPost

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key3=value3`;
const data = { key1: "value1", key2: "value2" };
const params = {
  method: "POST",
  payload: JSON.stringify(data),
};
const res = UrlFetchApp.fetch(url, params);
console.log(res.getContentText());

Result

Same as above.

3. Javascript

To doGet

Using fetch

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key1=value1&key2=value2&key3=value3`;
fetch(url)
  .then((res) => res.json())
  .then((res) => console.log(res));

Using XMLHttpRequest

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key1=value1&key2=value2&key3=value3`;
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => console.log(xhr.responseText);
xhr.onerror = () => console.log(xhr.response);
xhr.send(null);

Result

Same as above.

In above case, the result value can be retrieved as JSON object with res.json().

To doPost using fetch

Using fetch

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key3=value3`;
const data = { key1: "value1", key2: "value2" };
fetch(url, { method: "POST", body: JSON.stringify(data) })
  .then((res) => res.json())
  .then((res) => console.log(res));

Using XMLHttpRequest

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key3=value3`;
const data = { key1: "value1", key2: "value2" };
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.onload = () => console.log(xhr.responseText);
xhr.onerror = () => console.log(xhr.response);
xhr.send(JSON.stringify(data));

Result

{
  "method": "POST",
  "eventObject": {
    "parameters": { "key3": ["value3"] },
    "parameter": { "key3": "value3" },
    "postData": {
      "contents": "{\"key1\":\"value1\",\"key2\":\"value2\"}",
      "length": 33,
      "name": "postData",
      "type": "text/plain"
    },
    "contextPath": "",
    "contentLength": 33,
    "queryString": "key3=value3"
  }
}
  • In this case, the content type is text/plain and the properties without the value are not seen.

4. ajax

To doGet

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key1=value1&key2=value2&key3=value3`;
$.ajax({
  url: url,
  method: "GET",
  dataType: "json",
})
  .done((res) => console.log(res))
  .fail((err) => console.log(err));

Result

Same as above.

To doPost

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key3=value3`;
const data = { key1: "value1", key2: "value2" };
$.ajax({
  url: url,
  method: "POST",
  dataType: "json",
  data: JSON.stringify(data),
})
  .done((res) => console.log(JSON.stringify(res)))
  .fail((err) => console.log(err));

Result

Same as above.

5. Node.js

To doGet

const request = require("request");
let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key1=value1&key2=value2&key3=value3`;
request(
  {
    method: "GET",
    url: url,
    json: true,
  },
  (err, res, body) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log(body);
  }
);

Result

Same as above.

To doPost

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key3=value3`;
const data = { key1: "value1", key2: "value2" };
request(
  {
    method: "POST",
    url: url,
    body: JSON.stringify(data),
    json: true,
    followAllRedirects: true,
  },
  (err, res, body) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log(body);
  }
);

Result

{
  "method": "POST",
  "eventObject": {
    "queryString": "key3=value3",
    "contextPath": "",
    "parameters": { "key3": ["value3"] },
    "postData": {
      "contents": "\"{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\"",
      "length": 43,
      "name": "postData",
      "type": "application/json"
    },
    "parameter": { "key3": "value3" },
    "contentLength": 43
  }
}
  • In this case, eventObject.postData.contents can be retrieved by JSON.parse(JSON.parse(body.eventObject.postData.contents)). Please be careful this.

6. axios

To doGet

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key1=value1&key2=value2&key3=value3`;
axios
  .get(url)
  .then((res) => console.log(res.data))
  .catch((err) => console.log(err));

Result

Same as above.

To doPost

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key3=value3`;
const data = { key1: "value1", key2: "value2" };
axios
  .post(url, JSON.stringify(data))
  .then((res) => console.log(res.data))
  .catch((err) => console.log(err));

Result

Same as above.

7. angular

To doGet

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key1=value1&key2=value2&key3=value3`;
$http
  .get(url)
  .success((res) => console.log(res))
  .error((err) => console.log(err));

Result

Same as above.

To doPost

let url = "https://script.google.com/macros/s/###/exec";
url = `${url}?key3=value3`;
const data = { key1: "value1", key2: "value2" };
$http
  .post(url, JSON.stringify(data), {
    headers: { "Content-Type": "text/plain" },
  })
  .success((res) => console.log(res))
  .error((err) => console.log(err));
  • In this case, when "Content-Type": "text/plain" is not used, the error related to CORS occurs. Please be careful this.
  • Also, when "Content-Type": "application/json" is used, the error related to CORS occurs. Please be also careful this.

Result

{
  "method": "POST",
  "eventObject": {
    "queryString": "key3=value3",
    "contentLength": 33,
    "contextPath": "",
    "parameters": { "key3": ["value3"] },
    "parameter": { "key3": "value3" },
    "postData": {
      "contents": "{\"key1\":\"value1\",\"key2\":\"value2\"}",
      "length": 33,
      "name": "postData",
      "type": "text/plain"
    }
  }
}
  • In this case, the content type is text/plain and the properties without the value are not seen.

8. go

To doGet

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	url := "https://script.google.com/macros/s/###/exec"
	url += "?key1=value1&key2=value2&key3=value3"
	res, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))
    defer res.Body.Close()
}

Result

Same as above.

To doPost

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

func main() {
	url := "https://script.google.com/macros/s/###/exec"
	url += "?key3=value3"
	dataStr := struct {
		Key1 string `json:"key1"`
		Key2 string `json:"key2"`
	}{
		"value1",
		"value2",
	}
	data, _ := json.Marshal(dataStr)
	res, err := http.Post(url, "application/json", bytes.NewReader(data))
	if err != nil {
		log.Fatal(err)
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))
	defer res.Body.Close()
}

Result

{
  "method": "POST",
  "eventObject": {
    "parameters": { "key3": ["value3"] },
    "contentLength": 33,
    "contextPath": "",
    "queryString": "key3=value3",
    "parameter": { "key3": "value3" },
    "postData": {
      "contents": "{\"key1\":\"value1\",\"key2\":\"value2\"}",
      "length": 33,
      "name": "postData",
      "type": "application/json"
    }
  }
}
  • In this case, the content type is application/json and the properties without the value are not seen. By the way, the returned values from application/json and text/plain were the same.

9. python

To doGet

import requests

url = "https://script.google.com/macros/s/###/exec"
url += "?key1=value1&key2=value2&key3=value3"
res = requests.get(url)
print(res.text)

Result

Same as above.

To doPost

import json
import requests

url = "https://script.google.com/macros/s/###/exec"
url += "?key3=value3"
data = {"key1": "value1", "key2": "value2"}
res = requests.post(url, json.dumps(data), headers={"Content-Type": "application/json"})
print(res.text)

Result

{
  "method": "POST",
  "eventObject": {
    "contentLength": 36,
    "parameters": { "key3": ["value3"] },
    "parameter": { "key3": "value3" },
    "postData": {
      "contents": "{\"key2\": \"value2\", \"key1\": \"value1\"}",
      "length": 36,
      "name": "postData",
      "type": "application/json"
    },
    "queryString": "key3=value3",
    "contextPath": ""
  }
}
  • In this case, when "Content-Type": "application/json" is not used, postData has no property of contents. Please be careful this.

10. php

To doGet

$curl_handle = curl_init();
$url = 'https://script.google.com/macros/s/###/exec';
$url = $url.'?key1=value1&key2=value2&key3=value3';
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true);
$curl_data = curl_exec($curl_handle);
echo $curl_data;

Result

Same as above.

To doPost

$curl_handle = curl_init();
$url = 'https://script.google.com/macros/s/###/exec';
$url = $url.'?key3=value3';
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_POST, TRUE);
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, json_encode($data));
$curl_data = curl_exec($curl_handle);
echo $curl_data;

Result

Same as above.

11. powershell

To doGet

$url = "https://script.google.com/macros/s/###/exec"
$url = "${url}?key1=value1&key2=value2&key3=value3"
$resp = Invoke-WebRequest -Uri $url -Method Get
$resp.Content

Result

Same as above.

To doPost

$url = "https://script.google.com/macros/s/###/exec"
$url = "${url}?key1=value1&key2=value2&key3=value3"
$json = @"
{key1: "value1", key2: "value2"}
"@
$resp = Invoke-WebRequest -Uri $url -Method Post -ContentType "application/json" -Body $json
$resp.Content

Result

{
  "method": "POST",
  "eventObject": {
    "postData": {
      "contents": "{key1: \"value1\", key2: \"value2\"}",
      "length": 32,
      "name": "postData",
      "type": "application/json"
    },
    "parameters": { "key3": ["value3"] },
    "contextPath": "",
    "queryString": "key3=value3",
    "contentLength": 32,
    "parameter": { "key3": "value3" }
  }
}

References

TOP

 Share!