google/apiclient-services
Auto-generated Google API service definitions for the Google API PHP Client. Updated daily to reflect new/changed APIs and tagged weekly. Install via Composer (typically as a dependency of google/apiclient) to access specific Google service classes.
Installation:
Add the package via Composer (it’s bundled with google/apiclient):
composer require google/apiclient
Ensure you’re using google/apiclient v2.0+ for full google/apiclient-services compatibility.
First Use Case: Set up a Gmail API integration to fetch emails:
use Google\Client;
use Google\Service\Gmail;
// Configure OAuth 2.0 client
$client = new Client();
$client->setAuthConfig(__DIR__.'/credentials.json');
$client->addScope(Gmail::GMAIL_READONLY);
$client->setAccessType('offline');
$client->setPrompt('select_account');
// Create Gmail service
$gmail = new Gmail($client);
// Fetch user's inbox
$results = $gmail->users_messages->listUsersMessages('me', [
'maxResults' => 10,
'labelIds' => ['INBOX']
]);
$messages = $results->getMessages();
Where to Look First:
Service Provider Pattern:
Register the client as a singleton in Laravel’s AppServiceProvider:
public function register()
{
$this->app->singleton(Gmail::class, function ($app) {
$client = new Client();
$client->setAuthConfig(config('services.google.credentials'));
$client->addScope(Gmail::GMAIL_READONLY);
return new Gmail($client);
});
}
Facade Pattern:
Create a facade for cleaner syntax (e.g., GoogleGmail::fetchInbox()):
// app/Facades/GoogleGmail.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class GoogleGmail extends Facade
{
protected static function getFacadeAccessor() { return 'google.gmail'; }
}
Register the binding in AppServiceProvider:
$this->app->bind('google.gmail', function ($app) {
return $app->make(Gmail::class);
});
Queue-Based Batch Operations: Process large datasets (e.g., Drive files) asynchronously:
// app/Jobs/SyncDriveFiles.php
public function handle()
{
$service = new \Google\Service\Drive($this->client);
$results = $service->files->listFiles(['pageSize' => 100, 'fields' => 'nextPageToken, files(id, name)']);
foreach ($results->getFiles() as $file) {
// Process file (e.g., upload to S3, index in Scout)
SyncDriveFileJob::dispatch($file);
}
if ($results->getNextPageToken()) {
SyncDriveFiles::dispatch($this->client, $results->getNextPageToken());
}
}
Event-Driven Workflows: Trigger Laravel events after API calls:
// After uploading a file to Drive
event(new DriveFileUploaded($fileId, $userId));
// Listen in an event service provider
protected $listen = [
DriveFileUploaded::class => [
UpdateUserDashboard::class,
NotifyAdmin::class,
],
];
Filesystem Adapter:
Extend Laravel’s FilesystemAdapter to wrap Drive API calls:
// app/Filesystems/DriveAdapter.php
namespace App\Filesystems;
use Illuminate\Contracts\Filesystem\Filesystem;
use Google\Service\Drive;
class DriveAdapter implements Filesystem
{
public function put($path, $contents, $options = [])
{
$file = new \Google\Service\Drive\DriveFile([
'name' => basename($path),
'parents' => [config('services.google.drive_folder_id')],
]);
$service = new Drive($this->client);
return $service->files->create($file, ['data' => $contents]);
}
// Implement other Filesystem methods...
}
Register in config/filesystems.php:
'disks' => [
'drive' => [
'driver' => 'local', // or custom
'adapter' => App\Filesystems\DriveAdapter::class,
],
];
OAuth 2.0 Flow:
Sanctum or Passport for token storage.Passport:
$client = new Client();
$client->setAuthConfig(config('services.google.credentials'));
$client->setAccessToken($user->google_token); // Store token in DB
$client->setClientSecret(config('services.google.client_secret'));
Token Refresh:
Implement a GoogleAuthService to handle refresh tokens:
public function refreshToken($refreshToken)
{
$client = new Client();
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
$client->setRefreshToken($refreshToken);
$accessToken = $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
return $accessToken['access_token'];
}
Pagination Handling:
Use pageToken for large datasets:
$optParams = ['pageSize' => 100, 'fields' => 'nextPageToken, files(id)'];
$results = $service->files->listFiles($optParams);
do {
foreach ($results->getFiles() as $file) {
// Process file
}
$optParams['pageToken'] = $results->getNextPageToken();
$results = $service->files->listFiles($optParams);
} while ($results->getNextPageToken());
Error Handling:
Map Google API exceptions to Laravel’s HttpException:
try {
$results = $gmail->users_messages->get('me', $messageId);
} catch (\Google\Service\Exception $e) {
throw new \Illuminate\Http\Exception\HttpResponseException(
response()->json(['error' => $e->getMessage()], 400)
);
}
Laravel Queues: Offload heavy operations to queues:
SyncGmailLabelsJob::dispatch($userId)->onQueue('google');
Caching: Cache API responses (e.g., Drive file listings) with Laravel’s cache:
$cacheKey = "drive_files_{$userId}";
$files = cache()->remember($cacheKey, now()->addHours(1), function () use ($service, $userId) {
return $service->files->listFiles(['q' => "'$userId' in owners"]);
});
Testing:
Use Mockery to mock API responses:
$mock = Mockery::mock(Gmail::class);
$mock->shouldReceive('users_messages->get')
->once()
->andReturn((object) ['snippet' => 'Test email']);
$this->app->instance(Gmail::class, $mock);
Configuration:
Centralize Google API config in config/services/google.php:
return [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
'credentials' => __DIR__.'/../../credentials.json',
'scopes' => [
'gmail' => [Gmail::GMAIL_READONLY, Gmail::GMAIL_SEND],
'drive' => [Drive::DRIVE],
],
];
API Versioning:
Rate Limiting:
$retry = new \Google\ApiCore\Retry();
$client->setRetry($retry
How can I help you explore Laravel packages today?