Weave Code
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 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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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.

  2. 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();
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. 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);
        });
    }
    
  2. 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);
    });
    
  3. 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());
        }
    }
    
  4. 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,
        ],
    ];
    
  5. 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,
        ],
    ];
    

Workflows

  1. OAuth 2.0 Flow:

    • Use Laravel’s Sanctum or Passport for token storage.
    • Example with 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'));
      
  2. 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'];
    }
    
  3. 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());
    
  4. 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)
        );
    }
    

Integration Tips

  1. Laravel Queues: Offload heavy operations to queues:

    SyncGmailLabelsJob::dispatch($userId)->onQueue('google');
    
  2. 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"]);
    });
    
  3. 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);
    
  4. 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],
        ],
    ];
    

Gotchas and Tips

Pitfalls

  1. API Versioning:

    • Google APIs may deprecate endpoints without notice. Always check the changelog.
    • Fix: Implement CI/CD checks to validate API responses in staging.
  2. Rate Limiting:

    • Google APIs enforce quota limits (e.g., 1000 requests/100 seconds for Drive).
    • Fix: Use exponential backoff in retries:
      $retry = new \Google\ApiCore\Retry();
      $client->setRetry($retry
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope