RThomas
RThomas

Reputation: 10880

Sample python code provided by GCP - service variable undefined

The following sample code is provided by GCP to use the restAPI to list out group membership when you provide the group_id. Code sample can be found here. I can run the sample directly from the URI given, but when trying to run it from Python with the sample code provided. My IDE intellisense says that service in the very last line is an undefined variable. I can find nothing in GCP to indicate what library this might come from or what I should replace it with.

def search_transitive_memberships(service, parent, page_size):
  try:
    memberships = []
    next_page_token = ''
    while True:
      query_params = urlencode(
        {
          "page_size": page_size,
          "page_token": next_page_token
        }
      )
      request = service.groups().memberships().searchTransitiveMemberships(parent=parent)
      request.uri += "&" + query_params
      response = request.execute()

      if 'memberships' in response:
        memberships += response['memberships']

      if 'nextPageToken' in response:
        next_page_token = response['nextPageToken']
      else:
        next_page_token = ''

      if len(next_page_token) == 0:
        break;

    print(memberships)
  except Exception as e:
    print(e)

# Return results with a page size of 50
search_transitive_memberships(service, 'groups/01234567abcdefg', 50) ## <- service undefined

Appreciate assistance in identifying what I need to add to have service recognized.

Upvotes: 0

Views: 271

Answers (1)

RThomas
RThomas

Reputation: 10880

Ok, it appears what is missing from the code samples provided by GCP are the steps to build and use a service object.

Documentation on that can be found here: https://github.com/googleapis/google-api-python-client/blob/main/docs/start.md#building-and-calling-a-service

So for my sample above the last line would actually be:

service = build('cloudidentity', 'v1')
search_transitive_memberships(service, 'groups/01234567abcdefg', 50)
service.close

After importing build from googleapiclient.discovery

Github link above also details how to provide oauth creds for it to work.

Upvotes: 1

Related Questions