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 to access services like Gmail, Drive, and YouTube from your server. PHP 8+ and Composer install supported. Library is in maintenance mode: critical bug/security fixes only, no new features.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require google/apiclient
    

    Pin google/apiclient-services to a specific version in composer.json for production stability.

  2. First Use Case:

    require_once __DIR__.'/vendor/autoload.php';
    
    $client = new Google\Client();
    $client->setApplicationName('MyApp');
    $client->setDeveloperKey('YOUR_API_KEY');
    
    $service = new Google\Service\Books($client);
    $results = $service->volumes->listVolumes('PHP Laravel');
    print_r($results->getItems());
    
  3. Where to Look First:

    • Official Docs
    • examples/ directory in the package for practical examples.
    • API-specific guides (e.g., Gmail API).

Implementation Patterns

Core Workflows

  1. Authentication Patterns:

    • OAuth 2.0 (Web Apps):
      $client = new Google\Client();
      $client->setAuthConfig(__DIR__.'/credentials.json');
      $client->addScope(Google_Service_Drive::DRIVE);
      $client->setRedirectUri('https://your-app.com/oauth2callback');
      
    • Service Accounts:
      putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
      $client = new Google\Client();
      $client->useApplicationDefaultCredentials();
      $client->setSubject('user@example.com'); // Impersonate a user
      
    • API Keys (for public APIs):
      $client->setDeveloperKey('YOUR_API_KEY');
      
  2. Service Initialization:

    $drive = new Google\Service\Drive($client);
    $files = $drive->files->listFiles();
    
  3. Request/Response Handling:

    • Simple Requests:
      $results = $service->methodName($params);
      
    • Complex Requests (Object Mapping):
      $request = new Google\Service\Drive\FilesCreate();
      $request->setName('test.txt');
      $request->setMimeType('text/plain');
      $file = $drive->files->create($request, [
          'data' => fopen('test.txt', 'r'),
          'uploadType' => 'media',
          'fields' => 'id'
      ]);
      
  4. Pagination:

    $optParams = ['pageSize' => 10, 'pageToken' => $nextPageToken];
    $results = $service->list($optParams);
    $nextPageToken = $results->getNextPageToken();
    
  5. Error Handling:

    try {
        $results = $service->methodName($params);
    } catch (Google\Service\Exception $e) {
        if ($e->getCode() == 401) {
            // Handle unauthorized
        }
        log::error($e->getMessage());
    }
    

Integration Tips

  • Laravel Service Providers: Bind the client and services in AppServiceProvider:
    public function register()
    {
        $this->app->singleton(Google\Client::class, function ($app) {
            $client = new Google\Client();
            $client->setApplicationName(config('app.name'));
            $client->setAuthConfig(storage_path('app/google_credentials.json'));
            return $client;
        });
    }
    
  • Dependency Injection:
    public function __construct(private Google\Service\Drive $drive) {}
    
  • Configurable Scopes: Store scopes in config/google.php and load dynamically:
    $client->addScope(config('google.scopes.drive'));
    

Gotchas and Tips

Pitfalls

  1. Unintended API Bloat:

    • Avoid pulling all 200+ services. Use Google\Task\Composer::cleanup to trim dependencies.
    • Fix: Explicitly list required services in composer.json under "extra".
  2. Token Expiry:

    • Refresh tokens silently expire. Use setTokenCallback to log/handle updates:
      $client->setTokenCallback(function ($cacheKey, $accessToken) {
          cache()->forever($cacheKey, $accessToken);
      });
      
  3. Service Account Quirks:

    • Not all APIs support service accounts (e.g., YouTube). Check API docs.
    • Fix: Use OAuth 2.0 for unsupported APIs.
  4. Rate Limiting:

    • Google APIs enforce quotas. Monitor usage via Cloud Console.
    • Fix: Implement exponential backoff for 429 responses:
      if ($e->getCode() == 429) {
          sleep($e->getData()['retryAfter'] ?? 5);
          retry();
      }
      
  5. Caching Pitfalls:

    • PSR-6 caches may not handle token refreshes. Use setTokenCallback alongside caching:
      $client->setCache($cache);
      $client->setTokenCallback($tokenCallback);
      

Debugging

  1. Enable Debugging:

    $client->setDeveloperKey('YOUR_KEY');
    $client->setDebug(true);
    $client->setAccessType('offline');
    
    • Logs HTTP requests to stderr.
  2. Charles Proxy:

    • Configure the client to proxy through Charles:
      $client->setHttpClient(new \GuzzleHttp\Client([
          'proxy' => 'http://localhost:8888'
      ]));
      
  3. Common Errors:

    • 403: Access Denied: Missing scope or incorrect credentials.
    • 401: Unauthorized: Expired token. Use fetchAccessToken() to refresh.
    • 400: Invalid Request: Malformed request body. Validate against APIs Explorer.

Extension Points

  1. Custom HTTP Clients: Override the default Guzzle client:

    $client->setHttpClient(new CustomGuzzleClient());
    
  2. Middleware: Add request/response middleware:

    $client->setMiddleware([
        new class implements Google\Client\Middleware {
            public function __invoke($request, $next) {
                $request->setHeader('X-Custom-Header', 'value');
                return $next($request);
            }
        }
    ]);
    
  3. Batch Requests: Use Google\Batch\BatchRequest for parallel calls:

    $batch = new Google\Batch\BatchRequest($client);
    $batch->add($drive->files->get('fileId'), 'getFile');
    $batch->add($drive->files->listFiles(), 'listFiles');
    $responses = $batch->execute();
    
  4. Laravel Integration:

    • Queue Jobs:
      $job = new SyncGoogleData($drive);
      dispatch($job)->onQueue('google');
      
    • Events: Trigger events post-API call:
      event(new GoogleDataSynced($results));
      

Performance Tips

  1. Field Selection: Reduce payload size by specifying fields:

    $optParams = ['fields' => 'id,title'];
    $results = $service->list($optParams);
    
  2. Async Requests: Use ReactPHP with Guzzle for non-blocking calls:

    $loop = React\EventLoop\Factory::create();
    $connector = new React\Guzzle\HttpClient($loop);
    $client->setHttpClient($connector);
    
  3. Bulk Operations: For large datasets, use batch endpoints (e.g., Drive’s files.batchUpdate).

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.
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
anil/file-picker
broqit/fields-ai