LoginSignup
1
0

More than 3 years have passed since last update.

GCP CloudFunctionsからCloudAPIを呼び出す方法

Last updated at Posted at 2020-04-02

PythonのSDKでライブラリ化されてない関数をCloudFunctionsから呼び出したかったが、gcloudコマンドはCloudFunctionsに入ってないので(CloudFunctionsが動くコンピュートノードにgcloudはインストールされていない)CloudAPIを直接呼ぶ必要があった

CloudFunctionsからCloudAPIをRESTで呼びたい場合以下の様に認証をして呼び出すことが出来る

def hello_world(request):
    import google.auth
    from google.auth.transport import requests

    # Get the credentials and project ID from the environment.
    credentials, project = google.auth.default(
        scopes=['https://www.googleapis.com/auth/cloud-platform'])

    # Create a requests Session object with the credentials.
    session = requests.AuthorizedSession(credentials)

    # Make an authenticated API request
    response = session.get(
        'https://www.googleapis.com/storage/v1/b'.format(project),
        params={'project': project})
    response.raise_for_status()

    return response.text

API単体のテストだと、テストフォームが用意されているので、こちらが便利
https://cloud.google.com/storage/docs/json_api/v1/buckets/list

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0