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 Laravel Package

google/apiclient

Official Google APIs Client Library for PHP. Access services like Gmail, Drive, and YouTube from your server. Supports PHP 8+. In maintenance mode (critical fixes/security only). Install via Composer: google/apiclient.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require google/apiclient
    

    Pin google/apiclient-services to a specific version for production stability:

    "require": {
        "google/apiclient": "^2.15.0",
        "google/apiclient-services": "^2.15.0"
    }
    
  2. Basic Setup:

    require __DIR__.'/vendor/autoload.php';
    $client = new Google\Client();
    $client->setApplicationName('MyApp');
    $client->setDeveloperKey('YOUR_API_KEY'); // For API keys
    
  3. First API Call (e.g., Books API):

    $service = new Google\Service\Books($client);
    $results = $service->volumes->listVolumes('PHP', ['filter' => 'free-ebooks']);
    

Where to Look First


Implementation Patterns

Core Workflows

1. OAuth 2.0 Authentication (Web Apps)

$client = new Google\Client();
$client->setAuthConfig(__DIR__.'/client_secret.json');
$client->addScope(Google\Service\Drive::DRIVE);
$client->setRedirectUri('https://your-app.com/oauth2callback');

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);
}

2. Service Account Authentication (Server-to-Server)

putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google\Client();
$client->useApplicationDefaultCredentials();
$client->setSubject('user@example.com'); // Impersonate a user
$client->addScope(Google\Service\Drive::DRIVE);

3. API Service Initialization

$drive = new Google\Service\Drive($client);
$files = $drive->files->listFiles();

4. Batch Requests

$batch = new Google\BatchRequest($client);
$batch->add($drive->files->get('FILE_ID'));
$batch->add($drive->files->get('ANOTHER_FILE_ID'));
$responses = $batch->execute();

5. Media Upload/Download

// Upload
$file = new Google\Service\Drive\DriveFile([
    'name' => 'test.txt',
    'parents' => ['ROOT_FOLDER_ID']
]);
$content = fopen('test.txt', 'r');
$service->files->create($file, [
    'uploadType' => 'media',
    'mediaBody' => $content
]);

// Download
$file = $service->files->get('FILE_ID');
$content = $file->getDownloadMedia();
file_put_contents('downloaded.txt', $content);

Integration Tips

  • Laravel Integration: Store credentials in .env and use Laravel’s config() helper:
    $client = new Google\Client();
    $client->setAuthConfig(config('services.google.client_secret'));
    
  • Dependency Cleanup: Use Google\Task\Composer::cleanup in composer.json to trim unused services:
    "scripts": {
        "post-install-cmd": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": ["Drive", "YouTube"]
    }
    
  • PSR-6 Caching:
    $cache = new \Cache\Adapter\Filesystem\FilesystemCachePool(
        new \League\Flysystem\Filesystem(
            new \League\Flysystem\Adapter\Local(__DIR__.'/cache')
        )
    );
    $client->setCache($cache);
    

Gotchas and Tips

Pitfalls

  1. Service Account Limitations:

    • Not all APIs support service accounts (e.g., YouTube Data API). Check API docs.
    • Error: 403: Access Denied. Solution: Ensure scopes are correct and the service account has proper IAM roles.
  2. Token Expiry:

    • Refresh tokens expire after 6 months of inactivity. Use setTokenCallback to log new tokens:
      $client->setTokenCallback(function ($token) {
          file_put_contents('token.json', json_encode($token));
      });
      
  3. Quota Exhaustion:

    • Google APIs enforce quotas. Handle 429 Too Many Requests with exponential backoff:
      $client->setHttpClient(new \GuzzleHttp\Client([
          'delay' => 1000, // 1 second delay
          'timeout' => 30
      ]));
      
  4. CORS Issues:

  5. Deprecated APIs:

    • Some APIs (e.g., plus, analytics) are deprecated. Use alternatives like people or analyticsadmin.

Debugging Tips

  • Enable Debug Logging:
    $client->setDeveloperKey('YOUR_KEY');
    $client->setUseBatch(true);
    $client->setApplicationName('DebugApp');
    $client->setAuthConfig('client_secret.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');
    $client->setDebug(true); // Logs to STDOUT
    
  • Inspect Raw Requests: Use Charles Proxy or HTTP Toolkit to capture requests from google/apiclient.
  • Common Errors:
    • invalid_grant: Refresh token expired. Re-authenticate the user.
    • insufficient_permission: Missing scope or IAM role. Verify addScope() and service account permissions.

Extension Points

  1. Custom HTTP Client: Override the default Guzzle client for retries or middleware:

    $client->setHttpClient(new \GuzzleHttp\Client([
        'handler' => \GuzzleHttp\HandlerStack::create([
            new \GuzzleHttp\Middleware::retry(new \GuzzleHttp\RetryMiddleware())
        ])
    ]));
    
  2. Token Management: Extend Google_Auth_AssertionCredentials for custom token fetching:

    class CustomCredentials extends Google_Auth_AssertionCredentials {
        public function getAssertion() { /* ... */ }
    }
    $client->setAuth(new CustomCredentials(...));
    
  3. Service-Specific Extensions: Use traits or decorators to wrap API services:

    class DriveServiceDecorator {
        protected $service;
        public function __construct(Google\Service\Drive $service) {
            $this->service = $service;
        }
        public function uploadFile($filePath, $folderId) {
            // Custom logic
            $this->service->files->create(...);
        }
    }
    
  4. Event Listeners: Attach callbacks to the client for pre/post-request hooks:

    $client->addIOHandler(new class implements \Google\IO\IOHandlerInterface {
        public function handle($request, $next) {
            // Pre-request logic
            $response = $next($request);
            // Post-request logic
            return $response;
        }
    });
    

Configuration Quirks

  • setUseBatch(true): Enables batch requests but may fail if individual requests exceed size limits (~30MB).
  • setAccessType('offline'): Required for refresh tokens but may trigger additional OAuth prompts.
  • setApprovalPrompt('force'): Bypasses cached consent (useful for testing). Avoid in production.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4