run:R W Run
DIR
2026-04-08 19:42:57
R W Run
1.93 KB
2026-04-08 19:30:20
R W Run
10.02 KB
2026-04-08 19:30:20
R W Run
16.68 KB
2026-04-08 19:30:20
R W Run
11.29 KB
2026-04-08 19:30:21
R W Run
error_log
📄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
5The Google API Client Library enables you to work with Google APIs such as Gmail, Drive or YouTube on your server.
6
7These 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.
8
9**NOTE** The actively maintained (v2) version of this client requires PHP 5.4 or above. If you require support for PHP 5.2 or 5.3, use the v1 branch.
10
11## Google Cloud Platform
12
13For Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, we recommend using [GoogleCloudPlatform/google-cloud-php](https://github.com/googleapis/google-cloud-php) which is under active development.
14
15## Requirements ##
16* [PHP 5.4.0 or higher](https://www.php.net/)
17
18## Developer Documentation ##
19
20The [docs folder](docs/) provides detailed guides for using this library.
21
22## Installation ##
23
24You can use **Composer** or simply **Download the Release**
25
26### Composer
27
28The preferred method is via [composer](https://getcomposer.org/). Follow the
29[installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have
30composer installed.
31
32Once composer is installed, execute the following command in your project root to install this library:
33
34```sh
35composer require google/apiclient:"^2.7"
36```
37
38Finally, be sure to include the autoloader:
39
40```php
41require_once '/path/to/your-project/vendor/autoload.php';
42```
43
44This 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.
45
46#### Cleaning up unused services
47
48There are over 200 Google API services. The chances are good that you will not
49want them all. In order to avoid shipping these dependencies with your code,
50you can run the `Google_Task_Composer::cleanup` task and specify the services
51you want to keep in `composer.json`:
52
53```json
54{
55 "require": {
56 "google/apiclient": "^2.7"
57 },
58 "scripts": {
59 "post-update-cmd": "Google_Task_Composer::cleanup"
60 },
61 "extra": {
62 "google/apiclient-services": [
63 "Drive",
64 "YouTube"
65 ]
66 }
67}
68```
69
70This example will remove all services other than "Drive" and "YouTube" when
71`composer update` or a fresh `composer install` is run.
72
73**IMPORTANT**: If you add any services back in `composer.json`, you will need to
74remove the `vendor/google/apiclient-services` directory explicity for the
75change you made to have effect:
76
77```sh
78rm -r vendor/google/apiclient-services
79composer update
80```
81
82**NOTE**: This command performs an exact match on the service name, so to keep
83`YouTubeReporting` and `YouTubeAnalytics` as well, you'd need to add each of
84them explicitly:
85
86```json
87{
88 "extra": {
89 "google/apiclient-services": [
90 "Drive",
91 "YouTube",
92 "YouTubeAnalytics",
93 "YouTubeReporting"
94 ]
95 }
96}
97```
98
99### Download the Release
100
101If 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
102with the name `google-api-php-client-[RELEASE_NAME].zip` for a package including this library and its dependencies.
103
104Uncompress the zip file you download, and include the autoloader in your project:
105
106```php
107require_once '/path/to/google-api-php-client/vendor/autoload.php';
108```
109
110For additional installation and setup instructions, see [the documentation](docs/).
111
112## Examples ##
113See the [`examples/`](examples) directory for examples of the key client features. You can
114view them in your browser by running the php built-in web server.
115
116```
117$ php -S localhost:8000 -t examples/
118```
119
120And then browsing to the host and port you specified
121(in the above example, `http://localhost:8000`).
122
123### Basic Example ###
124
125```php
126// include your composer dependencies
127require_once 'vendor/autoload.php';
128
129$client = new Google_Client();
130$client->setApplicationName("Client_Library_Examples");
131$client->setDeveloperKey("YOUR_APP_KEY");
132
133$service = new Google_Service_Books($client);
134$optParams = array('filter' => 'free-ebooks');
135$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
136
137foreach ($results->getItems() as $item) {
138 echo $item['volumeInfo']['title'], "<br /> \n";
139}
140```
141
142### Authentication with OAuth ###
143
144> An example of this can be seen in [`examples/simple-file-upload.php`](examples/simple-file-upload.php).
145
1461. Follow the instructions to [Create Web Application Credentials](docs/oauth-web.md#create-authorization-credentials)
1471. Download the JSON credentials
1481. Set the path to these credentials using `Google_Client::setAuthConfig`:
149
150 ```php
151 $client = new Google_Client();
152 $client->setAuthConfig('/path/to/client_credentials.json');
153 ```
154
1551. Set the scopes required for the API you are going to call
156
157 ```php
158 $client->addScope(Google_Service_Drive::DRIVE);
159 ```
160
1611. Set your application's redirect URI
162
163 ```php
164 // Your redirect URI can be any registered URI, but in this example
165 // we redirect back to this same page
166 $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
167 $client->setRedirectUri($redirect_uri);
168 ```
169
1701. In the script handling the redirect URI, exchange the authorization code for an access token:
171
172 ```php
173 if (isset($_GET['code'])) {
174 $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
175 }
176 ```
177
178### Authentication with Service Accounts ###
179
180> An example of this can be seen in [`examples/service-account.php`](examples/service-account.php).
181
182Some APIs
183(such as the [YouTube Data API](https://developers.google.com/youtube/v3/)) do
184not support service accounts. Check with the specific API documentation if API
185calls return unexpected 401 or 403 errors.
186
1871. Follow the instructions to [Create a Service Account](docs/oauth-server.md#creating-a-service-account)
1881. Download the JSON credentials
1891. Set the path to these credentials using the `GOOGLE_APPLICATION_CREDENTIALS` environment variable:
190
191 ```php
192 putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
193 ```
194
1951. Tell the Google client to use your service account credentials to authenticate:
196
197 ```php
198 $client = new Google_Client();
199 $client->useApplicationDefaultCredentials();
200 ```
201
2021. Set the scopes required for the API you are going to call
203
204 ```php
205 $client->addScope(Google_Service_Drive::DRIVE);
206 ```
207
2081. 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:
209
210 ```php
211 $client->setSubject($user_to_impersonate);
212 ```
213
214### Making Requests ###
215
216The 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/).
217
218A JSON request to the [Datastore API](https://developers.google.com/apis-explorer/#p/datastore/v1beta3/datastore.projects.runQuery) would look like this:
219
220```json
221POST https://datastore.googleapis.com/v1beta3/projects/YOUR_PROJECT_ID:runQuery?key=YOUR_API_KEY
222
223{
224 "query": {
225 "kind": [{
226 "name": "Book"
227 }],
228 "order": [{
229 "property": {
230 "name": "title"
231 },
232 "direction": "descending"
233 }],
234 "limit": 10
235 }
236}
237```
238
239Using this library, the same call would look something like this:
240
241```php
242// create the datastore service class
243$datastore = new Google_Service_Datastore($client);
244
245// build the query - this maps directly to the JSON
246$query = new Google_Service_Datastore_Query([
247 'kind' => [
248 [
249 'name' => 'Book',
250 ],
251 ],
252 'order' => [
253 'property' => [
254 'name' => 'title',
255 ],
256 'direction' => 'descending',
257 ],
258 'limit' => 10,
259]);
260
261// build the request and response
262$request = new Google_Service_Datastore_RunQueryRequest(['query' => $query]);
263$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
264```
265
266However, as each property of the JSON API has a corresponding generated class, the above code could also be written like this:
267
268```php
269// create the datastore service class
270$datastore = new Google_Service_Datastore($client);
271
272// build the query
273$request = new Google_Service_Datastore_RunQueryRequest();
274$query = new Google_Service_Datastore_Query();
275// - set the order
276$order = new Google_Service_Datastore_PropertyOrder();
277$order->setDirection('descending');
278$property = new Google_Service_Datastore_PropertyReference();
279$property->setName('title');
280$order->setProperty($property);
281$query->setOrder([$order]);
282// - set the kinds
283$kind = new Google_Service_Datastore_KindExpression();
284$kind->setName('Book');
285$query->setKinds([$kind]);
286// - set the limit
287$query->setLimit(10);
288
289// add the query to the request and make the request
290$request->setQuery($query);
291$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
292```
293
294The 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.
295
296### Making HTTP Requests Directly ###
297
298If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly.
299
300If 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.
301
302The `authorize` method returns an authorized [Guzzle Client](http://docs.guzzlephp.org/), so any request made using the client will contain the corresponding authorization.
303
304```php
305// create the Google client
306$client = new Google_Client();
307
308/**
309 * Set your method for authentication. Depending on the API, This could be
310 * directly with an access token, API key, or (recommended) using
311 * Application Default Credentials.
312 */
313$client->useApplicationDefaultCredentials();
314$client->addScope(Google_Service_Plus::PLUS_ME);
315
316// returns a Guzzle HTTP Client
317$httpClient = $client->authorize();
318
319// make an HTTP request
320$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');
321```
322
323### Caching ###
324
325It 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:
326
327```php
328use League\Flysystem\Adapter\Local;
329use League\Flysystem\Filesystem;
330use Cache\Adapter\Filesystem\FilesystemCachePool;
331
332$filesystemAdapter = new Local(__DIR__.'/');
333$filesystem = new Filesystem($filesystemAdapter);
334
335$cache = new FilesystemCachePool($filesystem);
336$client->setCache($cache);
337```
338
339In this example we use [PHP Cache](http://www.php-cache.com/). Add this to your project with composer:
340
341```
342composer require cache/filesystem-adapter
343```
344
345### Updating Tokens ###
346
347When 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:
348
349```php
350$logger = new Monolog\Logger;
351$tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
352 $logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
353};
354$client->setTokenCallback($tokenCallback);
355```
356
357### Debugging Your HTTP Request using Charles ###
358
359It 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:
360
361```php
362// FOR DEBUGGING ONLY
363$httpClient = new GuzzleHttp\Client([
364 'proxy' => 'localhost:8888', // by default, Charles runs on localhost port 8888
365 'verify' => false, // otherwise HTTPS requests will fail.
366]);
367
368$client = new Google_Client();
369$client->setHttpClient($httpClient);
370```
371
372Now all calls made by this library will appear in the Charles UI.
373
374One 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`.
375
376### Controlling HTTP Client Configuration Directly
377
378Google 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.
379
380Let's say, for instance, we wished to apply a referrer to each request.
381
382```php
383use GuzzleHttp\Client;
384
385$httpClient = new Client([
386 'headers' => [
387 'referer' => 'mysite.com'
388 ]
389]);
390
391$client = new Google_Client();
392$client->setHttpClient($httpClient);
393```
394
395Other Guzzle features such as [Handlers and Middleware](http://docs.guzzlephp.org/en/stable/handlers-and-middleware.html) offer even more control.
396
397### Service Specific Examples ###
398
399YouTube: https://github.com/youtube/api-samples/tree/master/php
400
401## How Do I Contribute? ##
402
403Please 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.
404
405## Frequently Asked Questions ##
406
407### What do I do if something isn't working? ###
408
409For 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
410
411If 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.
412
413### I want an example of X! ###
414
415If 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!
416
417### Why does Google_..._Service have weird names? ###
418
419The _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.
420
421### How do I deal with non-JSON response types? ###
422
423Some 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:
424
425```
426$opt_params = array(
427 'alt' => "json"
428);
429```
430
431### How do I set a field to null? ###
432
433The library strips out nulls from the objects sent to the Google APIs as its 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.
434
435## Code Quality ##
436
437Run 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.
438
439 phpunit tests/
440
441### Coding Style
442
443To check for coding style violations, run
444
445```
446vendor/bin/phpcs src --standard=style/ruleset.xml -np
447```
448
449To automatically fix (fixable) coding style violations, run
450
451```
452vendor/bin/phpcbf src --standard=style/ruleset.xml
453```
454