Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Apiclient Services Laravel Package

google/apiclient-services

Auto-generated PHP classes for Google API services, updated daily and tagged weekly. Installed automatically with the Google API PHP Client, it provides typed service classes and resources for calling Google APIs directly from PHP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require google/apiclient-services
    

    Ensure google/apiclient (v2.0+) is also installed as a dependency.

  2. First Use Case: Authenticate and List Drive Files

    use Google\Service\Drive;
    use Google\Client;
    
    // Configure OAuth 2.0 client
    $client = new Client();
    $client->setAuthConfig('path/to/service-account.json'); // Or use user credentials
    $client->addScope(Drive::DRIVE);
    
    // Create Drive service
    $driveService = new Drive($client);
    
    // List files in root folder
    $files = $driveService->files->listFiles([
        'pageSize' => 10,
        'fields' => 'files(id, name, mimeType)'
    ])->getFiles();
    
    return $files;
    
  3. Laravel Integration:

    • Register the client in AppServiceProvider:
      public function register()
      {
          $this->app->singleton(Drive::class, function ($app) {
              $client = new Client();
              $client->setAuthConfig(config('services.google.drive'));
              $client->addScope(Drive::DRIVE);
              return new Drive($client);
          });
      }
      
    • Access via dependency injection:
      public function index(Drive $driveService)
      {
          $files = $driveService->files->listFiles(['pageSize' => 10])->getFiles();
          return response()->json($files);
      }
      

Where to Look First

  • Reference Documentation: Auto-generated API docs for all supported services (Drive, Gmail, Calendar, etc.).
  • google/apiclient: Core library for OAuth, HTTP clients, and shared utilities.
  • Laravel Service Provider: Centralize client configuration and dependency injection.
  • Error Handling: Google_Service_Exception and Google_Auth_Exception for debugging.

Implementation Patterns

Usage Patterns

  1. Service Provider Pattern

    • Centralize client initialization in AppServiceProvider or a dedicated GoogleServiceProvider.
    • Example:
      $this->app->bind('google.drive', function ($app) {
          $client = new Client();
          $client->setAuthConfig(config('services.google.drive'));
          $client->addScope(Drive::DRIVE);
          return new Drive($client);
      });
      
    • Inject via constructor or facade:
      use Illuminate\Support\Facades\GoogleDrive;
      
      public function upload()
      {
          $file = GoogleDrive::files()->create([
              'name' => 'test.txt',
              'mimeType' => 'text/plain'
          ], upload('test.txt'));
      }
      
  2. Facade Pattern

    • Create facades for cleaner syntax (e.g., GoogleDrive, GoogleGmail).
    • Example facade:
      class GoogleDrive extends Facade
      {
          protected static function getFacadeAccessor() { return 'google.drive'; }
      }
      
  3. Job-Based Batch Processing

    • Use Laravel queues for large-scale operations (e.g., Drive file migrations).
    • Example job:
      class SyncDriveFilesJob implements ShouldQueue
      {
          public function handle(Drive $driveService)
          {
              $results = $driveService->files->listFiles([
                  'pageSize' => 100,
                  'fields' => 'nextPageToken, files(id, name)'
              ]);
      
              foreach ($results->getFiles() as $file) {
                  // Process file (e.g., store metadata in DB)
              }
      
              if ($results->getNextPageToken()) {
                  SyncDriveFilesJob::dispatch($driveService, $results->getNextPageToken());
              }
          }
      }
      
  4. Event-Driven Workflows

    • Trigger Laravel events after API calls (e.g., DriveFileUploaded).
    • Example:
      event(new DriveFileUploaded($fileId, $userId));
      
      // In an event listener:
      public function handle(DriveFileUploaded $event)
      {
          // Notify user or update UI
      }
      
  5. Filesystem Adapter

    • Extend Illuminate\Filesystem\FilesystemAdapter to wrap Drive API calls.
    • Example:
      class DriveAdapter extends FilesystemAdapter
      {
          public function put($path, $contents, $options = [])
          {
              $file = $this->driveService->files->create([
                  'name' => basename($path),
                  'parents' => [$this->rootFolderId]
              ], $contents);
      
              return $file->getId();
          }
      }
      
    • Register in config/filesystems.php:
      'disks' => [
          'drive' => [
              'driver' => 'google-drive',
              'root_folder_id' => env('GOOGLE_DRIVE_ROOT_FOLDER'),
          ],
      ],
      

Workflows

  1. OAuth Flow

    • Use Laravel’s Sanctum or Passport for token management.
    • Example:
      $client = new Client();
      $client->setAuthConfig(config('services.google'));
      $client->setAccessToken($user->google_token); // From Sanctum/Passport
      
  2. Retry Logic

    • Handle rate limits (429) and server errors (500) with exponential backoff.
    • Example:
      use Google\ApiCore\ApiException;
      
      try {
          $response = $driveService->files->get($fileId);
      } catch (ApiException $e) {
          if ($e->getStatusCode() === 429) {
              sleep(2 ** $e->getRetryInfo()->getExponent());
              return $this->handle($request);
          }
          throw $e;
      }
      
  3. Pagination

    • Use pageToken for large datasets.
    • Example:
      $optParams = ['pageSize' => 100, 'fields' => 'nextPageToken, files(id)'];
      $results = $driveService->files->listFiles($optParams);
      
      do {
          $files = $results->getFiles();
          // Process files
          $optParams['pageToken'] = $results->getNextPageToken();
          $results = $driveService->files->listFiles($optParams);
      } while ($results->getNextPageToken());
      
  4. Async Operations

    • Offload long-running tasks to queues.
    • Example:
      SyncGmailLabelsJob::dispatch($gmailService, $labelId)->onQueue('google');
      

Integration Tips

  • Laravel Config: Store API credentials in .env and config/services.php:
    'google' => [
        'drive' => [
            'key' => env('GOOGLE_DRIVE_KEY'),
            'scopes' => [Drive::DRIVE],
        ],
    ],
    
  • Environment-Specific Config: Use config('services.google.drive') in different environments (dev/staging/prod).
  • Testing: Mock API responses with Mockery or Vcr:
    $mock = Mockery::mock(Drive::class);
    $mock->shouldReceive('files')->andReturnSelf();
    $mock->shouldReceive('listFiles')->andReturn(new Google_Service_Drive_DriveFileList());
    
  • Logging: Log API calls and errors:
    try {
        $response = $driveService->files->get($fileId);
    } catch (Exception $e) {
        Log::error('Google Drive API error', ['exception' => $e]);
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. API Deprecation

    • Google APIs evolve rapidly. Monitor Google’s changelog and update dependencies regularly.
    • Fix: Use composer why-not google/apiclient-services to check for updates.
  2. OAuth Scopes

    • Request only necessary scopes (e.g., Drive::DRIVE vs. Drive::DRIVE_READONLY).
    • Fix: Review scope documentation and revoke unused scopes.
  3. Rate Limits

    • Unauthorized requests or bursts may trigger 429 errors.
    • Fix: Implement exponential backoff (see Google’s retry guide).
  4. Token Expiry

    • Access tokens expire (1 hour by default). Refresh tokens may also expire.
    • Fix: Use Laravel’s Sanctum or Passport for token persistence and refresh logic.
  5. Large File Uploads

    • Files >5MB require resumable uploads.
    • Fix: Use Google\Service\Drive\DriveFile with mediaUpload:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource