• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..29-Apr-2022-

src/H29-Apr-2022-4,6042,790

LICENSEH A D28-Apr-202210 KiB204169

README.mdH A D28-Apr-202217.5 KiB478343

SECURITY.mdH A D28-Apr-2022329 84

composer.jsonH A D28-Apr-20221.5 KiB5049

README.md

1![](https://github.com/googleapis/google-api-php-client/workflows/.github/workflows/tests.yml/badge.svg)
2
3# Google APIs Client Library for PHP #
4
5<dl>
6  <dt>Reference Docs</dt><dd><a href="https://googleapis.github.io/google-api-php-client/main/">https://googleapis.github.io/google-api-php-client/main/</a></dd>
7  <dt>License</dt><dd>Apache 2.0</dd>
8</dl>
9
10The Google API Client Library enables you to work with Google APIs such as Gmail, Drive or YouTube on your server.
11
12These client libraries are officially supported by Google.  However, the libraries are considered complete and are in maintenance mode. This means that we will address critical bugs and security issues but will not add any new features.
13
14## Google Cloud Platform
15
16For Google Cloud Platform APIs such as [Datastore][cloud-datastore], [Cloud Storage][cloud-storage], [Pub/Sub][cloud-pubsub], and [Compute Engine][cloud-compute], we recommend using the Google Cloud client libraries. For a complete list of supported Google Cloud client libraries, see [googleapis/google-cloud-php](https://github.com/googleapis/google-cloud-php).
17
18[cloud-datastore]: https://github.com/googleapis/google-cloud-php-datastore
19[cloud-pubsub]: https://github.com/googleapis/google-cloud-php-pubsub
20[cloud-storage]: https://github.com/googleapis/google-cloud-php-storage
21[cloud-compute]: https://github.com/googleapis/google-cloud-php-compute
22
23## Requirements ##
24* [PHP 5.6.0 or higher](https://www.php.net/)
25
26## Developer Documentation ##
27
28The [docs folder](docs/) provides detailed guides for using this library.
29
30## Installation ##
31
32You can use **Composer** or simply **Download the Release**
33
34### Composer
35
36The preferred method is via [composer](https://getcomposer.org/). Follow the
37[installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have
38composer installed.
39
40Once composer is installed, execute the following command in your project root to install this library:
41
42```sh
43composer require google/apiclient:^2.12.1
44```
45
46Finally, be sure to include the autoloader:
47
48```php
49require_once '/path/to/your-project/vendor/autoload.php';
50```
51
52This library relies on `google/apiclient-services`. That library provides up-to-date API wrappers for a large number of Google APIs. In order that users may make use of the latest API clients, this library does not pin to a specific version of `google/apiclient-services`. **In order to prevent the accidental installation of API wrappers with breaking changes**, it is highly recommended that you pin to the [latest version](https://github.com/googleapis/google-api-php-client-services/releases) yourself prior to using this library in production.
53
54#### Cleaning up unused services
55
56There are over 200 Google API services. The chances are good that you will not
57want them all. In order to avoid shipping these dependencies with your code,
58you can run the `Google\Task\Composer::cleanup` task and specify the services
59you want to keep in `composer.json`:
60
61```json
62{
63    "require": {
64        "google/apiclient": "^2.12.1"
65    },
66    "scripts": {
67        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
68    },
69    "extra": {
70        "google/apiclient-services": [
71            "Drive",
72            "YouTube"
73        ]
74    }
75}
76```
77
78This example will remove all services other than "Drive" and "YouTube" when
79`composer update` or a fresh `composer install` is run.
80
81**IMPORTANT**: If you add any services back in `composer.json`, you will need to
82remove the `vendor/google/apiclient-services` directory explicitly for the
83change you made to have effect:
84
85```sh
86rm -r vendor/google/apiclient-services
87composer update
88```
89
90**NOTE**: This command performs an exact match on the service name, so to keep
91`YouTubeReporting` and `YouTubeAnalytics` as well, you'd need to add each of
92them explicitly:
93
94```json
95{
96    "extra": {
97        "google/apiclient-services": [
98            "Drive",
99            "YouTube",
100            "YouTubeAnalytics",
101            "YouTubeReporting"
102        ]
103    }
104}
105```
106
107### Download the Release
108
109If you prefer not to use composer, you can download the package in its entirety. The [Releases](https://github.com/googleapis/google-api-php-client/releases) page lists all stable versions. Download any file
110with the name `google-api-php-client-[RELEASE_NAME].zip` for a package including this library and its dependencies.
111
112Uncompress the zip file you download, and include the autoloader in your project:
113
114```php
115require_once '/path/to/google-api-php-client/vendor/autoload.php';
116```
117
118For additional installation and setup instructions, see [the documentation](docs/).
119
120## Examples ##
121See the [`examples/`](examples) directory for examples of the key client features. You can
122view them in your browser by running the php built-in web server.
123
124```
125$ php -S localhost:8000 -t examples/
126```
127
128And then browsing to the host and port you specified
129(in the above example, `http://localhost:8000`).
130
131### Basic Example ###
132
133```php
134// include your composer dependencies
135require_once 'vendor/autoload.php';
136
137$client = new Google\Client();
138$client->setApplicationName("Client_Library_Examples");
139$client->setDeveloperKey("YOUR_APP_KEY");
140
141$service = new Google\Service\Books($client);
142$query = 'Henry David Thoreau';
143$optParams = [
144  'filter' => 'free-ebooks',
145];
146$results = $service->volumes->listVolumes($query, $optParams);
147
148foreach ($results->getItems() as $item) {
149  echo $item['volumeInfo']['title'], "<br /> \n";
150}
151```
152
153### Authentication with OAuth ###
154
155> An example of this can be seen in [`examples/simple-file-upload.php`](examples/simple-file-upload.php).
156
1571. Follow the instructions to [Create Web Application Credentials](docs/oauth-web.md#create-authorization-credentials)
1581. Download the JSON credentials
1591. Set the path to these credentials using `Google\Client::setAuthConfig`:
160
161    ```php
162    $client = new Google\Client();
163    $client->setAuthConfig('/path/to/client_credentials.json');
164    ```
165
1661. Set the scopes required for the API you are going to call
167
168    ```php
169    $client->addScope(Google\Service\Drive::DRIVE);
170    ```
171
1721. Set your application's redirect URI
173
174    ```php
175    // Your redirect URI can be any registered URI, but in this example
176    // we redirect back to this same page
177    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
178    $client->setRedirectUri($redirect_uri);
179    ```
180
1811. In the script handling the redirect URI, exchange the authorization code for an access token:
182
183    ```php
184    if (isset($_GET['code'])) {
185        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
186    }
187    ```
188
189### Authentication with Service Accounts ###
190
191> An example of this can be seen in [`examples/service-account.php`](examples/service-account.php).
192
193Some APIs
194(such as the [YouTube Data API](https://developers.google.com/youtube/v3/)) do
195not support service accounts. Check with the specific API documentation if API
196calls return unexpected 401 or 403 errors.
197
1981. Follow the instructions to [Create a Service Account](docs/oauth-server.md#creating-a-service-account)
1991. Download the JSON credentials
2001. Set the path to these credentials using the `GOOGLE_APPLICATION_CREDENTIALS` environment variable:
201
202    ```php
203    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
204    ```
205
2061. Tell the Google client to use your service account credentials to authenticate:
207
208    ```php
209    $client = new Google\Client();
210    $client->useApplicationDefaultCredentials();
211    ```
212
2131. Set the scopes required for the API you are going to call
214
215    ```php
216    $client->addScope(Google\Service\Drive::DRIVE);
217    ```
218
2191. If you have delegated domain-wide access to the service account and you want to impersonate a user account, specify the email address of the user account using the method setSubject:
220
221    ```php
222    $client->setSubject($user_to_impersonate);
223    ```
224
225#### How to use a specific JSON key
226
227If you want to a specific JSON key instead of using `GOOGLE_APPLICATION_CREDENTIALS` environment variable, you can do this:
228
229```php
230$jsonKey = [
231   'type' => 'service_account',
232   // ...
233];
234$client = new Google\Client();
235$client->setAuthConfig($jsonKey);
236```
237
238### Making Requests ###
239
240The classes used to call the API in [google-api-php-client-services](https://github.com/googleapis/google-api-php-client-services) are autogenerated. They map directly to the JSON requests and responses found in the [APIs Explorer](https://developers.google.com/apis-explorer/#p/).
241
242A JSON request to the [Datastore API](https://developers.google.com/apis-explorer/#p/datastore/v1beta3/datastore.projects.runQuery) would look like this:
243
244```json
245POST https://datastore.googleapis.com/v1beta3/projects/YOUR_PROJECT_ID:runQuery?key=YOUR_API_KEY
246
247{
248    "query": {
249        "kind": [{
250            "name": "Book"
251        }],
252        "order": [{
253            "property": {
254                "name": "title"
255            },
256            "direction": "descending"
257        }],
258        "limit": 10
259    }
260}
261```
262
263Using this library, the same call would look something like this:
264
265```php
266// create the datastore service class
267$datastore = new Google\Service\Datastore($client);
268
269// build the query - this maps directly to the JSON
270$query = new Google\Service\Datastore\Query([
271    'kind' => [
272        [
273            'name' => 'Book',
274        ],
275    ],
276    'order' => [
277        'property' => [
278            'name' => 'title',
279        ],
280        'direction' => 'descending',
281    ],
282    'limit' => 10,
283]);
284
285// build the request and response
286$request = new Google\Service\Datastore\RunQueryRequest(['query' => $query]);
287$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
288```
289
290However, as each property of the JSON API has a corresponding generated class, the above code could also be written like this:
291
292```php
293// create the datastore service class
294$datastore = new Google\Service\Datastore($client);
295
296// build the query
297$request = new Google\Service\Datastore_RunQueryRequest();
298$query = new Google\Service\Datastore\Query();
299//   - set the order
300$order = new Google\Service\Datastore_PropertyOrder();
301$order->setDirection('descending');
302$property = new Google\Service\Datastore\PropertyReference();
303$property->setName('title');
304$order->setProperty($property);
305$query->setOrder([$order]);
306//   - set the kinds
307$kind = new Google\Service\Datastore\KindExpression();
308$kind->setName('Book');
309$query->setKinds([$kind]);
310//   - set the limit
311$query->setLimit(10);
312
313// add the query to the request and make the request
314$request->setQuery($query);
315$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
316```
317
318The method used is a matter of preference, but *it will be very difficult to use this library without first understanding the JSON syntax for the API*, so it is recommended to look at the [APIs Explorer](https://developers.google.com/apis-explorer/#p/) before using any of the services here.
319
320### Making HTTP Requests Directly ###
321
322If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly.
323
324If you are installing this client only to authenticate your own HTTP client requests, you should use [`google/auth`](https://github.com/googleapis/google-auth-library-php#call-the-apis) instead.
325
326The `authorize` method returns an authorized [Guzzle Client](http://docs.guzzlephp.org/), so any request made using the client will contain the corresponding authorization.
327
328```php
329// create the Google client
330$client = new Google\Client();
331
332/**
333 * Set your method for authentication. Depending on the API, This could be
334 * directly with an access token, API key, or (recommended) using
335 * Application Default Credentials.
336 */
337$client->useApplicationDefaultCredentials();
338$client->addScope(Google\Service\Plus::PLUS_ME);
339
340// returns a Guzzle HTTP Client
341$httpClient = $client->authorize();
342
343// make an HTTP request
344$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');
345```
346
347### Caching ###
348
349It is recommended to use another caching library to improve performance. This can be done by passing a [PSR-6](https://www.php-fig.org/psr/psr-6/) compatible library to the client:
350
351```php
352use League\Flysystem\Adapter\Local;
353use League\Flysystem\Filesystem;
354use Cache\Adapter\Filesystem\FilesystemCachePool;
355
356$filesystemAdapter = new Local(__DIR__.'/');
357$filesystem        = new Filesystem($filesystemAdapter);
358
359$cache = new FilesystemCachePool($filesystem);
360$client->setCache($cache);
361```
362
363In this example we use [PHP Cache](http://www.php-cache.com/). Add this to your project with composer:
364
365```
366composer require cache/filesystem-adapter
367```
368
369### Updating Tokens ###
370
371When using [Refresh Tokens](https://developers.google.com/identity/protocols/OAuth2InstalledApp#offline) or [Service Account Credentials](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#overview), it may be useful to perform some action when a new access token is granted. To do this, pass a callable to the `setTokenCallback` method on the client:
372
373```php
374$logger = new Monolog\Logger();
375$tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
376  $logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
377};
378$client->setTokenCallback($tokenCallback);
379```
380
381### Debugging Your HTTP Request using Charles ###
382
383It is often very useful to debug your API calls by viewing the raw HTTP request. This library supports the use of [Charles Web Proxy](https://www.charlesproxy.com/documentation/getting-started/). Download and run Charles, and then capture all HTTP traffic through Charles with the following code:
384
385```php
386// FOR DEBUGGING ONLY
387$httpClient = new GuzzleHttp\Client([
388    'proxy' => 'localhost:8888', // by default, Charles runs on localhost port 8888
389    'verify' => false, // otherwise HTTPS requests will fail.
390]);
391
392$client = new Google\Client();
393$client->setHttpClient($httpClient);
394```
395
396Now all calls made by this library will appear in the Charles UI.
397
398One additional step is required in Charles to view SSL requests. Go to **Charles > Proxy > SSL Proxying Settings** and add the domain you'd like captured. In the case of the Google APIs, this is usually `*.googleapis.com`.
399
400### Controlling HTTP Client Configuration Directly
401
402Google API Client uses [Guzzle](http://docs.guzzlephp.org/) as its default HTTP client. That means that you can control your HTTP requests in the same manner you would for any application using Guzzle.
403
404Let's say, for instance, we wished to apply a referrer to each request.
405
406```php
407use GuzzleHttp\Client;
408
409$httpClient = new Client([
410    'headers' => [
411        'referer' => 'mysite.com'
412    ]
413]);
414
415$client = new Google\Client();
416$client->setHttpClient($httpClient);
417```
418
419Other Guzzle features such as [Handlers and Middleware](http://docs.guzzlephp.org/en/stable/handlers-and-middleware.html) offer even more control.
420
421### Service Specific Examples ###
422
423YouTube: https://github.com/youtube/api-samples/tree/master/php
424
425## How Do I Contribute? ##
426
427Please see the [contributing](.github/CONTRIBUTING.md) page for more information. In particular, we love pull requests - but please make sure to sign the contributor license agreement.
428
429## Frequently Asked Questions ##
430
431### What do I do if something isn't working? ###
432
433For support with the library the best place to ask is via the google-api-php-client tag on StackOverflow: https://stackoverflow.com/questions/tagged/google-api-php-client
434
435If there is a specific bug with the library, please [file an issue](https://github.com/googleapis/google-api-php-client/issues) in the GitHub issues tracker, including an example of the failing code and any specific errors retrieved. Feature requests can also be filed, as long as they are core library requests, and not-API specific: for those, refer to the documentation for the individual APIs for the best place to file requests. Please try to provide a clear statement of the problem that the feature would address.
436
437### I want an example of X! ###
438
439If X is a feature of the library, file away! If X is an example of using a specific service, the best place to go is to the teams for those specific APIs - our preference is to link to their examples rather than add them to the library, as they can then pin to specific versions of the library. If you have any examples for other APIs, let us know and we will happily add a link to the README above!
440
441### Why do some Google\Service classes have weird names? ###
442
443The _Google\Service_ classes are generally automatically generated from the API discovery documents: https://developers.google.com/discovery/. Sometimes new features are added to APIs with unusual names, which can cause some unexpected or non-standard style naming in the PHP classes.
444
445### How do I deal with non-JSON response types? ###
446
447Some services return XML or similar by default, rather than JSON, which is what the library supports. You can request a JSON response by adding an 'alt' argument to optional params that is normally the last argument to a method call:
448
449```php
450$opt_params = array(
451  'alt' => "json"
452);
453```
454
455### How do I set a field to null? ###
456
457The library strips out nulls from the objects sent to the Google APIs as it is the default value of all of the uninitialized properties. To work around this, set the field you want to null to `Google\Model::NULL_VALUE`. This is a placeholder that will be replaced with a true null when sent over the wire.
458
459## Code Quality ##
460
461Run the PHPUnit tests with PHPUnit. You can configure an API key and token in BaseTest.php to run all calls, but this will require some setup on the Google Developer Console.
462
463    phpunit tests/
464
465### Coding Style
466
467To check for coding style violations, run
468
469```
470vendor/bin/phpcs src --standard=style/ruleset.xml -np
471```
472
473To automatically fix (fixable) coding style violations, run
474
475```
476vendor/bin/phpcbf src --standard=style/ruleset.xml
477```
478