Google API Client Library for PHP

repository·main·Indexed 27 days ago

https://github.com/googleapis/google-api-php-client

An officially supported PHP library for server-side integration with Google APIs such as Gmail, Drive, and YouTube. It provides tools for managing authentication (OAuth 2.0, Service Accounts, and API Keys), making API requests via generated service classes or an authorized Guzzle client, and handling PSR-6 caching. The library is currently in maintenance mode and utilizes google/apiclient-services for API wrappers.

Tokens
14.6K
Snippets
51
Records
98
Agent score
92%

What's inside google-api-php-client

  1. Choose an authentication method for Google APIs

    main

    The Google PHP Client Library supports several authentication methods depending on your use case:

    • API Keys: For accessing public data or services that do not require user authorization.
    • OAuth 2.0 for Webservers: For applications that need to access data on behalf of a user (e.g., accessing a user's Google Drive).
    • OAuth 2.0 Service Accounts: For server-to-server communication where no user interaction is required (e.g., a backend service accessing Google Cloud resources).
    • ID Token Verification: For identifying users without granting the application permission to make Google API calls on their behalf.
  2. Authentication types: Simple vs. Authorized access

    main

    Google APIs use two primary authentication patterns:

    1. Simple API access (API keys): Used for calls that do not access private user data. You must provide an API key to identify your project for quota and billing purposes. Keep this key private.

    2. Authorized API access (OAuth 2.0): Used for calls accessing private user data. This requires:

      • Scopes: Permissions declared by the API (e.g., read-only vs. read-write).
      • Tokens: An access token (used for calls, expires frequently) and a refresh token (used to get new access tokens, does not expire).
      • Client Credentials: A Client ID and Client Secret created in the Google Cloud Console to identify your application. There are specific types for Web applications, Installed applications, and Service Accounts.
  3. Set a field to null in API requests

    main
    The library automatically strips out null values from objects sent to Google APIs because null is the default value for uninitialized properties. To explicitly send a null value for a specific field, assign it the constant Google\Model::NULL_VALUE. The library will replace this placeholder with a true null when transmitting the request.
  4. Initialize the Google Client object

    main

    The Google\Client object is the primary container for configuration and authentication in the library. You must instantiate it and set your application name and, if using simple API access, your developer key.

    $client = new Google\Client();
    $client->setApplicationName("My Application");
    $client->setDeveloperKey("MY_SIMPLE_API_KEY");
  5. Perform a Resumable File Upload

    main

    For large files, use resumable uploads to split the data into chunks across multiple requests. This allows for resuming the upload if a connection error occurs.

    To implement this:

    1. Set the client to deferred mode using $client->setDefer(true).
    2. Initialize a Google\Http\MediaFileUpload object with the client, the request, the MIME type, and a chunk size.
    3. Iterate through the file in chunks using $media->nextChunk($chunk) until the upload is complete.
    4. Reset the client to non-deferred mode using $client->setDefer(false) once finished.
    $file = new Google\Service\Drive\DriveFile();
    $file->title = "Big File";
    $chunkSizeBytes = 1 * 1024 * 1024;
    
    // Call the API with the media upload, defer so it doesn't immediately return.
    $client->setDefer(true);
    $request = $service->files->insert($file);
    
    // Create a media file upload to represent our upload process.
    $media = new Google\Http\MediaFileUpload(
      $client,
      $request,
      'text/plain',
      null,
      true,
      $chunkSizeBytes
    );
    $media->setFileSize(filesize("path/to/file"));
    
    // Upload the various chunks. $status will be false until the process is
    // complete.
    $status = false;
    $handle = fopen("path/to/file", "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
     }
    
    // The final value of $status will be the data from the API for the object
    // that has been uploaded.
    $result = false;
    if($status != false) {
      $result = $status;
    }
    
    fclose($handle);
    // Reset to the client to execute requests immediately in the future.
    $client->setDefer(false);
  6. Use OAuth 2.0 for Server-to-Server Applications

    main

    For server-to-server interactions (where no end-user is directly involved), use a Service Account. This is often called "two-legged OAuth" (2LO). Service accounts are ideal for applications working with their own data (e.g., Google Cloud Datastore) or for applications requiring domain-wide delegation in a G Suite/Google Workspace environment.

    Workflow Overview:

    1. Create a service account in the Google Developers Console.
    2. (Optional) Delegate domain-wide authority if accessing user data in a G Suite domain.
    3. Use the service account credentials to request an access token.
    4. Use the access token to call Google APIs.
  7. Perform a Simple Media Upload

    main

    Use a simple upload when you want to upload file data without specifying additional metadata. The file content is passed directly as the request body. This is the easiest method but offers the least control over file properties.

    $file = new Google\Service\Drive\DriveFile();
    $result = $service->files->insert($file, array(
      'data' => file_get_contents("path/to/file"),
      'mimeType' => 'application/octet-stream',
      'uploadType' => 'media'
    ));