You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现带认证的Google Apps Script doPost/doGet API(支持curl调用)

Authenticating Curl/Script Requests to Google Apps Script doPost/doGet for Google Workspace Accounts

Got it, let's tackle this problem step by step. When switching to a Google Workspace (formerly G Suite) account, your Apps Script web app can't be accessed anonymously anymore—so we need to authenticate your curl/script requests with valid enterprise credentials. Here are the most reliable solutions:

Solution 1: Use OAuth 2.0 Access Tokens with Curl

The simplest way to authenticate is to include a valid Google Workspace account access token in your request headers. Here's how to do it:

Step 1: Get an Access Token

Use the Google Cloud CLI (gcloud) to fetch a token tied to your enterprise account:

# Log in with your enterprise account
gcloud auth login --account=your-enterprise-email@company.com

# Print the access token (valid for ~1 hour)
gcloud auth print-access-token

Step 2: Call the Web App with Curl

Replace YOUR_GAS_DEPLOYMENT_ID with your web app's deployment ID, then run this curl command:

curl -X POST "https://script.google.com/macros/s/YOUR_GAS_DEPLOYMENT_ID/exec" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Question title",
    "description": "This is a description.",
    "items": [
      { "question": "How old are you?" },
      { "question": "What'\''s your name" },
      { "question": "Please tell me the phone number" }
    ]
  }'

This will authenticate your request as your enterprise account, bypassing the login redirect.

Solution 2: Use the Apps Script API (Execution API) Correctly

You mentioned trying the Execution API but struggling—let's fix that. The key is to either call your existing doPost function with the right parameter structure, or simplify things by extracting the form-creation logic into a standalone function.

Option A: Call the doPost Function Directly

The Execution API requires you to reconstruct the e parameter that doPost expects. Use this curl command (replace YOUR_SCRIPT_ID):

curl -X POST "https://script.googleapis.com/v1/scripts/YOUR_SCRIPT_ID:run" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "function": "doPost",
    "parameters": [{
      "postData": {
        "contents": "{\"title\": \"Question title\", \"description\": \"This is a description.\", \"items\": [{\"question\": \"How old are you?\"}, {\"question\": \"What'\''s your name\"}, {\"question\": \"Please tell me the phone number\"}]}",
        "type": "application/json"
      }
    }]
  }'

Option B: Simplify with a Standalone Function

Modify your Apps Script code to extract the form-creation logic into a separate function—this makes the Execution API call cleaner:

function createForm(formData) {
  const { title, description, items } = formData;
  if (!title) {
    return { message: 'please input title!', error: true };
  }

  // Create form logic (same as original doPost)
  const form = FormApp.create(title);
  form.setDescription(description);
  const itemIdList = [];
  
  items.forEach(item => {
    const textItem = form.addTextItem();
    textItem.setTitle(item.question);
    itemIdList.push({ question: item.question, item_id: textItem.getId() });
  });

  return {
    published_url: form.getPublishedUrl(),
    edit_url: form.getEditUrl(),
    error: false,
    form_id: form.getId(),
    item_id_list: itemIdList
  };
}

// Keep doPost for browser-based requests
function doPost(e) {
  const postData = JSON.parse(e.postData.getDataAsString());
  const result = createForm(postData);
  return ContentService.createTextOutput(JSON.stringify(result))
    .setMimeType(ContentService.MimeType.JSON);
}

Now call the createForm function directly via the Execution API:

curl -X POST "https://script.googleapis.com/v1/scripts/YOUR_SCRIPT_ID:run" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "function": "createForm",
    "parameters": [{
      "title": "Question title",
      "description": "This is a description.",
      "items": [
        { "question": "How old are you?" },
        { "question": "What'\''s your name" },
        { "question": "Please tell me the phone number" }
      ]
    }]
  }'

Prerequisite: Enable the Apps Script API in your Google Cloud Console (linked to your Workspace account's project).

Solution 3: Service Account Authentication (For Server-Side Scripts)

If you need to run automated, long-running scripts (not just one-off curl calls), use a Google Cloud Service Account:

Step 1: Set Up the Service Account

  1. Go to the Google Cloud Console, create a service account, and download its JSON key file.
  2. Share your Apps Script project with the service account's email address (grant Editor permissions).

Step 2: Use Python to Call the Web App

Here's a Python example using the google-auth library:

import google.auth
from google.auth.transport.requests import Request
import requests

# Load service account credentials
credentials, _ = google.auth.load_credentials_from_file('service-account-key.json')
# Add required scopes
credentials = credentials.with_scopes([
    'https://www.googleapis.com/auth/forms',
    'https://www.googleapis.com/auth/script.external_request'
])

# Refresh credentials if needed
if not credentials.valid:
    credentials.refresh(Request())

# Call the GAS web app
url = "https://script.google.com/macros/s/YOUR_GAS_DEPLOYMENT_ID/exec"
headers = {
    'Authorization': f'Bearer {credentials.token}',
    'Content-Type': 'application/json'
}
payload = {
    "title": "Question title",
    "description": "This is a description.",
    "items": [
        {"question": "How old are you?"},
        {"question": "What's your name"},
        {"question": "Please tell me the phone number"}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())

Key Notes

  • Ensure your Apps Script web app is deployed with access set to "Anyone in [Your Domain] with the link" (this allows authenticated enterprise users/service accounts to access it).
  • Always include the required OAuth scopes: https://www.googleapis.com/auth/forms (for creating forms) and https://www.googleapis.com/auth/script.external_request (for accessing the web app/Execution API).

内容的提问来源于stack exchange,提问作者yoshio1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:26:22