Roman Shytskou
Roman Shytskou

Reputation: 1

Adding multiple users JSON for Google Directory API (Python)

When I try to add users: In this way I can only add one user, but I will need to add multiple users from the JSON file.

req =  [
            {
                "primaryEmail": "[email protected]",
                "name": {
                            "givenName": "UserName",
                            "familyName": "UserLastName"
                        },
                "suspended": False,
                "password": "my password",
                "hashFunction": "SHA-1",
                "changePasswordAtNextLogin": False,
                "agreedToTerms": True,
                "ipWhitelisted": False                
            },
            {
                "primaryEmail": "[email protected]",
                "name": {
                            "givenName": "FirstName",
                          "familyName": "LastName"
                       },
                "suspended": False,
                "password": "my password",
                "hashFunction": "SHA-1",
                "changePasswordAtNextLogin": False,
                "agreedToTerms": True,
                "ipWhitelisted": False               

            }
        ]
users = service.users().insert(body=req).execute()

I get some error like:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?alt=json returned "Invalid Input: primary_user_email">

How can I add multiple users in this way?

Upvotes: 0

Views: 322

Answers (1)

Vasil Nikolov
Vasil Nikolov

Reputation: 757

You would have to use a BatchRequest if you want to send multiple actions in one API call. Here is an example from the Python documentation provided by google

def list_animals(request_id, response, exception):
  if exception is not None:
    # Do something with the exception
    pass
  else:
    # Do something with the response
    pass

def list_farmers(request_id, response):
  """Do something with the farmers list response."""
  pass

service = build('farm', 'v2')

batch = service.new_batch_http_request()

batch.add(service.animals().list(), callback=list_animals)
batch.add(service.farmers().list(), callback=list_farmers)
batch.execute()

You can read more about the method here : https://developers.google.com/admin-sdk/directory/v1/guides/batch

Or use the github repository directly (where the example came from): https://googleapis.github.io/google-api-python-client/docs/batch.html

The only thing you need to be aware of is the threshold of requests send per second/minute/hour , but google would error out if you exceed the limit and you would have to limit the requests using an Exponential Backoff

Upvotes: 1

Related Questions