source: vendor/google/apiclient/README.md

Last change on this file was e3d4e0a, checked in by Vlado 222039 <vlado.popovski@…>, 7 days ago

Upload project files

  • Property mode set to 100644
File size: 18.7 KB
Line 
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**NOTE**: please check to see if the package you'd like to install is available in our
6list of [Google cloud packages](https://cloud.google.com/php/docs/reference) first, as
7these are the recommended libraries.
8
9<dl>
10 <dt>Reference Docs</dt><dd><a href="https://googleapis.github.io/google-api-php-client/">https://googleapis.github.io/google-api-php-client/</a></dd>
11 <dt>License</dt><dd>Apache 2.0</dd>
12</dl>
13
14The Google API Client Library enables you to work with Google APIs such as Gmail, Drive or YouTube on your server.
15
16These 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.
17
18## Google Cloud Platform
19
20For 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).
21
22[cloud-datastore]: https://github.com/googleapis/google-cloud-php-datastore
23[cloud-pubsub]: https://github.com/googleapis/google-cloud-php-pubsub
24[cloud-storage]: https://github.com/googleapis/google-cloud-php-storage
25[cloud-compute]: https://github.com/googleapis/google-cloud-php-compute
26
27## Requirements ##
28* [PHP 8.0 or higher](https://www.php.net/)
29
30## Developer Documentation ##
31
32The [docs folder](docs/) provides detailed guides for using this library.
33
34## Installation ##
35
36You can use **Composer** or simply **Download the Release**
37
38### Composer
39
40The preferred method is via [composer](https://getcomposer.org/). Follow the
41[installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have
42composer installed.
43
44Once composer is installed, execute the following command in your project root to install this library:
45
46```sh
47composer require google/apiclient:^2.15.0
48```
49
50If you're facing a timeout error then either increase the timeout for composer by adding the env flag as `COMPOSER_PROCESS_TIMEOUT=600 composer install` or you can put this in the `config` section of the composer schema:
51```
52{
53 "config": {
54 "process-timeout": 600
55 }
56}
57```
58
59Finally, be sure to include the autoloader:
60
61```php
62require_once '/path/to/your-project/vendor/autoload.php';
63```
64
65This 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.
66
67#### Cleaning up unused services
68
69There are over 200 Google API services. The chances are good that you will not
70want them all. In order to avoid shipping these dependencies with your code,
71you can run the `Google\Task\Composer::cleanup` task and specify the services
72you want to keep in `composer.json`:
73
74```json
75{
76 "require": {
77 "google/apiclient": "^2.15.0"
78 },
79 "scripts": {
80 "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
81 },
82 "extra": {
83 "google/apiclient-services": [
84 "Drive",
85 "YouTube"
86 ]
87 }
88}
89```
90
91This example will remove all services other than "Drive" and "YouTube" when
92`composer update` or a fresh `composer install` is run.
93
94**IMPORTANT**: If you add any services back in `composer.json`, you will need to
95remove the `vendor/google/apiclient-services` directory explicitly for the
96change you made to have effect:
97
98```sh
99rm -r vendor/google/apiclient-services
100composer update
101```
102
103**NOTE**: This command performs an exact match on the service name, so to keep
104`YouTubeReporting` and `YouTubeAnalytics` as well, you'd need to add each of
105them explicitly:
106
107```json
108{
109 "extra": {
110 "google/apiclient-services": [
111 "Drive",
112 "YouTube",
113 "YouTubeAnalytics",
114 "YouTubeReporting"
115 ]
116 }
117}
118```
119
120### Download the Release
121
122If 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
123with the name `google-api-php-client-[RELEASE_NAME].zip` for a package including this library and its dependencies.
124
125Uncompress the zip file you download, and include the autoloader in your project:
126
127```php
128require_once '/path/to/google-api-php-client/vendor/autoload.php';
129```
130
131For additional installation and setup instructions, see [the documentation](docs/).
132
133## Examples ##
134See the [`examples/`](examples) directory for examples of the key client features. You can
135view them in your browser by running the php built-in web server.
136
137```
138$ php -S localhost:8000 -t examples/
139```
140
141And then browsing to the host and port you specified
142(in the above example, `http://localhost:8000`).
143
144### Basic Example ###
145
146```php
147// include your composer dependencies
148require_once 'vendor/autoload.php';
149
150$client = new Google\Client();
151$client->setApplicationName("Client_Library_Examples");
152$client->setDeveloperKey("YOUR_APP_KEY");
153
154$service = new Google\Service\Books($client);
155$query = 'Henry David Thoreau';
156$optParams = [
157 'filter' => 'free-ebooks',
158];
159$results = $service->volumes->listVolumes($query, $optParams);
160
161foreach ($results->getItems() as $item) {
162 echo $item['volumeInfo']['title'], "<br /> \n";
163}
164```
165
166### Authentication with OAuth ###
167
168> An example of this can be seen in [`examples/simple-file-upload.php`](examples/simple-file-upload.php).
169
1701. Follow the instructions to [Create Web Application Credentials](docs/oauth-web.md#create-authorization-credentials)
1711. Download the JSON credentials
1721. Set the path to these credentials using `Google\Client::setAuthConfig`:
173
174 ```php
175 $client = new Google\Client();
176 $client->setAuthConfig('/path/to/client_credentials.json');
177 ```
178
1791. Set the scopes required for the API you are going to call
180
181 ```php
182 $client->addScope(Google\Service\Drive::DRIVE);
183 ```
184
1851. Set your application's redirect URI
186
187 ```php
188 // Your redirect URI can be any registered URI, but in this example
189 // we redirect back to this same page
190 $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
191 $client->setRedirectUri($redirect_uri);
192 ```
193
1941. In the script handling the redirect URI, exchange the authorization code for an access token:
195
196 ```php
197 if (isset($_GET['code'])) {
198 $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
199 }
200 ```
201
202### Authentication with Service Accounts ###
203
204> An example of this can be seen in [`examples/service-account.php`](examples/service-account.php).
205
206Some APIs
207(such as the [YouTube Data API](https://developers.google.com/youtube/v3/)) do
208not support service accounts. Check with the specific API documentation if API
209calls return unexpected 401 or 403 errors.
210
2111. Follow the instructions to [Create a Service Account](docs/oauth-server.md#creating-a-service-account)
2121. Download the JSON credentials
2131. Set the path to these credentials using the `GOOGLE_APPLICATION_CREDENTIALS` environment variable:
214
215 ```php
216 putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
217 ```
218
2191. Tell the Google client to use your service account credentials to authenticate:
220
221 ```php
222 $client = new Google\Client();
223 $client->useApplicationDefaultCredentials();
224 ```
225
2261. Set the scopes required for the API you are going to call
227
228 ```php
229 $client->addScope(Google\Service\Drive::DRIVE);
230 ```
231
2321. 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:
233
234 ```php
235 $client->setSubject($user_to_impersonate);
236 ```
237
238#### How to use a specific JSON key
239
240If you want to a specific JSON key instead of using `GOOGLE_APPLICATION_CREDENTIALS` environment variable, you can do this:
241
242```php
243$jsonKey = [
244 'type' => 'service_account',
245 // ...
246];
247$client = new Google\Client();
248$client->setAuthConfig($jsonKey);
249```
250
251### Making Requests ###
252
253The 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/).
254
255A JSON request to the [Datastore API](https://developers.google.com/apis-explorer/#p/datastore/v1beta3/datastore.projects.runQuery) would look like this:
256
257```
258POST https://datastore.googleapis.com/v1beta3/projects/YOUR_PROJECT_ID:runQuery?key=YOUR_API_KEY
259```
260```json
261{
262 "query": {
263 "kind": [{
264 "name": "Book"
265 }],
266 "order": [{
267 "property": {
268 "name": "title"
269 },
270 "direction": "descending"
271 }],
272 "limit": 10
273 }
274}
275```
276
277Using this library, the same call would look something like this:
278
279```php
280// create the datastore service class
281$datastore = new Google\Service\Datastore($client);
282
283// build the query - this maps directly to the JSON
284$query = new Google\Service\Datastore\Query([
285 'kind' => [
286 [
287 'name' => 'Book',
288 ],
289 ],
290 'order' => [
291 'property' => [
292 'name' => 'title',
293 ],
294 'direction' => 'descending',
295 ],
296 'limit' => 10,
297]);
298
299// build the request and response
300$request = new Google\Service\Datastore\RunQueryRequest(['query' => $query]);
301$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
302```
303
304However, as each property of the JSON API has a corresponding generated class, the above code could also be written like this:
305
306```php
307// create the datastore service class
308$datastore = new Google\Service\Datastore($client);
309
310// build the query
311$request = new Google\Service\Datastore_RunQueryRequest();
312$query = new Google\Service\Datastore\Query();
313// - set the order
314$order = new Google\Service\Datastore_PropertyOrder();
315$order->setDirection('descending');
316$property = new Google\Service\Datastore\PropertyReference();
317$property->setName('title');
318$order->setProperty($property);
319$query->setOrder([$order]);
320// - set the kinds
321$kind = new Google\Service\Datastore\KindExpression();
322$kind->setName('Book');
323$query->setKinds([$kind]);
324// - set the limit
325$query->setLimit(10);
326
327// add the query to the request and make the request
328$request->setQuery($query);
329$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
330```
331
332The 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.
333
334### Making HTTP Requests Directly ###
335
336If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly.
337
338If 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.
339
340The `authorize` method returns an authorized [Guzzle Client](http://docs.guzzlephp.org/), so any request made using the client will contain the corresponding authorization.
341
342```php
343// create the Google client
344$client = new Google\Client();
345
346/**
347 * Set your method for authentication. Depending on the API, This could be
348 * directly with an access token, API key, or (recommended) using
349 * Application Default Credentials.
350 */
351$client->useApplicationDefaultCredentials();
352$client->addScope(Google\Service\Plus::PLUS_ME);
353
354// returns a Guzzle HTTP Client
355$httpClient = $client->authorize();
356
357// make an HTTP request
358$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');
359```
360
361### Caching ###
362
363It 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:
364
365```php
366use League\Flysystem\Adapter\Local;
367use League\Flysystem\Filesystem;
368use Cache\Adapter\Filesystem\FilesystemCachePool;
369
370$filesystemAdapter = new Local(__DIR__.'/');
371$filesystem = new Filesystem($filesystemAdapter);
372
373$cache = new FilesystemCachePool($filesystem);
374$client->setCache($cache);
375```
376
377In this example we use [PHP Cache](http://www.php-cache.com/). Add this to your project with composer:
378
379```
380composer require cache/filesystem-adapter
381```
382
383### Updating Tokens ###
384
385When 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:
386
387```php
388$logger = new Monolog\Logger();
389$tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
390 $logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
391};
392$client->setTokenCallback($tokenCallback);
393```
394
395### Debugging Your HTTP Request using Charles ###
396
397It 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:
398
399```php
400// FOR DEBUGGING ONLY
401$httpClient = new GuzzleHttp\Client([
402 'proxy' => 'localhost:8888', // by default, Charles runs on localhost port 8888
403 'verify' => false, // otherwise HTTPS requests will fail.
404]);
405
406$client = new Google\Client();
407$client->setHttpClient($httpClient);
408```
409
410Now all calls made by this library will appear in the Charles UI.
411
412One 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`.
413
414### Controlling HTTP Client Configuration Directly
415
416Google 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.
417
418Let's say, for instance, we wished to apply a referrer to each request.
419
420```php
421use GuzzleHttp\Client;
422
423$httpClient = new Client([
424 'headers' => [
425 'referer' => 'mysite.com'
426 ]
427]);
428
429$client = new Google\Client();
430$client->setHttpClient($httpClient);
431```
432
433Other Guzzle features such as [Handlers and Middleware](http://docs.guzzlephp.org/en/stable/handlers-and-middleware.html) offer even more control.
434
435### Partial Consent and Granted Scopes
436
437When using OAuth2 3LO (e.g. you're a client requesting credentials from a 3rd
438party, such as in the [simple file upload example](examples/simple-file-upload.php)),
439you may want to take advantage of Partial Consent.
440
441To allow clients to only grant certain scopes in the OAuth2 screen, pass the
442querystring parameter for `enable_serial_consent` when generating the
443authorization URL:
444
445```php
446$authUrl = $client->createAuthUrl($scope, ['enable_serial_consent' => 'true']);
447```
448
449Once the flow is completed, you can see which scopes were granted by calling
450`getGrantedScope` on the OAuth2 object:
451
452```php
453// Space-separated string of granted scopes if it exists, otherwise null.
454echo $client->getOAuth2Service()->getGrantedScope();
455```
456
457### Service Specific Examples ###
458
459YouTube: https://github.com/youtube/api-samples/tree/master/php
460
461## How Do I Contribute? ##
462
463Please 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.
464
465## Frequently Asked Questions ##
466
467### What do I do if something isn't working? ###
468
469For 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
470
471If 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.
472
473### I want an example of X! ###
474
475If 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!
476
477### Why do some Google\Service classes have weird names? ###
478
479The _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.
480
481### How do I deal with non-JSON response types? ###
482
483Some 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:
484
485```php
486$opt_params = array(
487 'alt' => "json"
488);
489```
490
491### How do I set a field to null? ###
492
493The 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.
494
495## Code Quality ##
496
497Run 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.
498
499 phpunit tests/
500
501### Coding Style
502
503To check for coding style violations, run
504
505```
506vendor/bin/phpcs src --standard=style/ruleset.xml -np
507```
508
509To automatically fix (fixable) coding style violations, run
510
511```
512vendor/bin/phpcbf src --standard=style/ruleset.xml
513```
Note: See TracBrowser for help on using the repository browser.