Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

HTTP POST from Apps Script to Google Cloud Run Function

I previously wrote in the "Authentication Issue - Cloud Run Functions" topic that I keep getting a "401 Unauthorized" error code while testing a Cloud Run Function. This issue has been resolved with the appropriate roles. I have a new problem now 😬.

I want to send an HTTP POST request (with JSON data) to a Cloud Run Function using Apps Script, but I don't see any such entry in the Cloud Run Function logs. The Apps Script API is enabled within my GCP project.

The roles associated with my account: Owner, Cloud Run Source Developer, Service Account User, Service Usage Consumer

The roles associated with the Service Account I specifically created for Cloud Run Functions: Cloud Functions Developer, Cloud Run Admin, Service Account Token Creator, Service Account User

Some info from my code:

appsscript.json:

...
"oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/script.container.ui",
    "https://www.googleapis.com/auth/cloud-platform",
    "openid"
  ],
...

 The request parameters, and the request:

...
var
options = { "method": "post", "contentType": "application/json", "payload": jsonData, "headers": { "Authorization": "bearer "+ScriptApp.getIdentityToken() // gcloud auth print-identity-token } }; ... // url: Cloud Run Functions URL var response = UrlFetchApp.fetch(url, options);

My simple Cloud Run Functions Python code that would handle the request:

import functions_framework

@functions_framework.http
def http_function(request):
    content_type = request.headers["content-type"]
    if content_type == "application/json":
        try:
            request_json = request.get_json(silent=True)
            data = request_json

        except Exception as e:
            return "No JSON data provided", 400

    return f"{data}"

Can someone help me to finally get my function to accept the request?

If I missed sharing any important info, please let me know.

0 1 127
1 REPLY 1

Hi @NSzabolcs,

Welcome to Google Cloud Community!

This issue was already addressed in a similar post on Stack Overflow. Here's the solution from @theMaster that resolved the problem: “You need permission run.routes.invoke on the account that is providing the identity token.So, you need to add either Cloud Run Admin or Cloud Run Invoker on the user account.” 

Was this helpful? If so, please accept this answer as “Solution”. If you need additional assistance, reply here within 2 business days and I’ll be happy to help.

 

.