Christian Lange
Christian Lange

Reputation: 61

Google Directory API - batch add members to a group

I am using the Google Admin SDK to create, update and delete mailing lists (aka groups).

Everything works fine so far and I can create a new group and add members to it. But: Every adding of a member takes about 1s so I was thinking of a batch request to add several users to a group at once.

In the Google Admin interface it is easy to add several users at once but I didn't find any way to implement this via the API.

Is there a way to do so or do I have to loop through every user?


This works but takes a lot of time if I have to do it for every single user:

    $service = new Google_Service_Directory($this->getGoogleClient());

    $user = new Google_Service_Directory_Member();
    $user->setEmail('[email protected]');
    $user->setRole('MEMBER');
    $user->setType('USER');

    $service->members->insert($group_id, $user);

Upvotes: 3

Views: 2442

Answers (2)

Paridhi Yadav
Paridhi Yadav

Reputation: 11

While using the method of Christian Lange I was getting this error -

Argument 1 passed to Google\Client::execute() must implement interface Psr\Http\Message\RequestInterface, instance of Google\Http\Batch given,

So I used this instead

$client->setUseBatch(true);

$service = new Google_Service_Directory($client);

$batch = $service->createBatch();

foreach ($emails as $email)
    {
        $user = new Google_Service_Directory_Member(array('email' => $email,
            'kind' => 'member',
            'role' => 'MEMBER',
            'type' => 'USER'));

        $list = $service->members->insert($key, $user);

        $batch->add($list);
    }
$resultsBatch = $batch->execute();

Upvotes: 1

Christian Lange
Christian Lange

Reputation: 61

finally I found a solution on my own: The Admin SDK comes with a Batch class :)

To get batch requests working these steps are necessary:

When initiating the Google Client add the following line to the code

    $client->setUseBatch(true);

then you can initiate the batch object

    $batch = new Google_Http_Batch($client);

a little modification on the code posted above brings me to this code

    foreach($arr_users as $user)
    {
            $userdata = new Google_Service_Directory_Member();
            $userdata->setEmail($user);
            $userdata->setRole('MEMBER');
            $userdata->setType('USER');
            $batch->add($service->members->insert($temp_list_name, $userdata));
    }

finally you have to execute the request which is done by this line:

    $client->execute($batch);

that's all and it works perfectly

Upvotes: 3

Related Questions