I want to trigger some Google Cloud APIs from Google Cloud Functions. Could you please help me how I can do this. How to get the Auth TOken and all for this ?
If someone have some example use case that would be great.
As explained in the doc:
(You can) access Google Cloud Platform APIs from Cloud Function by using a service account to act on your behalf. The service account provides Application Default Credentials for your functions.
...
API client libraries that use application default credentials automatically obtain the built-in service account credentials from the Cloud Functions host at runtime. By default, the client authenticates using the
[email protected]service account.
So, you don't need to get an Auth Token.
You'll find several examples in the official Firebase Cloud Functions samples page. For example, this one for the Translate API or this one for the Vision API.
There is also a set of examples in the Cloud Functions doc (which covers Cloud Functions written in Python, Go or Java).
I think you can use something similar to this code.
It was not tested.
For example to call the Method: projects.locations.instances.get
def make_func(request):
# Get the access token from the metadata server
metadata_server_token_url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token?scopes=https://www.googleapis.com/auth/cloud-platform'
token_request_headers = {'Metadata-Flavor': 'Google'}
token_response = requests.get(metadata_server_token_url, headers=token_request_headers)
token_response_decoded = token_response.content.decode("utf-8")
jwt = json.loads(token_response_decoded)['access_token']
# Use the api you mentioned to create the function
response = requests.post('https://datafusion.googleapis.com/v1beta1/projects/your-project/locations/us-central1/instances/your-instance',
headers={'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(jwt)} )
if response:
return 'Success! Function Created'
else:
return str(response.json())