Invoking Google Cloud Function from python using service account for authentication
I

1

8

I have a cloud function with trigger type set to HTTP and also have a service account which is having permissions to Invoke the cloud function. I want to invoke the cloud function from a python script. I am using the following script to invoke the function:

from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

credentials = service_account.Credentials.from_service_account_file('/path/to/service-account-credentials.json')

scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/cloud-platform'])

authed_http = AuthorizedHttp(scoped_credentials)

response = authed_http.request('GET', 'https://test-123456.cloudfunctions.net/my-cloud-function')

print(response.status)

I am getting Unauthorized ( 401 ) error in response. Is this the correct way of invocation?

Irenairene answered 9/4, 2020 at 5:58 Comment(0)
M
12

To be able to call your cloud function you need an ID Token against a Cloud Functions end point

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession


url = 'https://test-123456.cloudfunctions.net/my-cloud-function'

creds = service_account.IDTokenCredentials.from_service_account_file(
       '/path/to/service-account-credentials.json', target_audience=url)

authed_session = AuthorizedSession(creds)

# make authenticated request and print the response, status_code
resp = authed_session.get(url)
print(resp.status_code)
print(resp.text)

Mukluk answered 9/4, 2020 at 8:35 Comment(3)
Thank you so much, Ive been trying figure this out for ages!Dot
Do you have a post request example or a documentation pointing for the same too?Dunagan
Have an example file for service-account-credentials.json that I can reference?Villagomez

© 2022 - 2024 — McMap. All rights reserved.