且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Google BigQuery API PHP凭证

更新时间:2023-02-07 13:57:38

默认凭据由适用于PHP的Google API客户端库,2.0.0及更新版本。要使用它们,请调用useApplicationDefaultCredentials:

  $ client = new Google_Client(); 
$ client-> useApplicationDefaultCredentials();

然后,使用凭据访问API服务,如下所示:

  $ client-> setScopes(['https://www.googleapis.com/auth/books']); 
$ service = new Google_Service_Books($ client);
$ results = $ service-> volumes-> listVolumes('Henry David Thoreau');

我建议查看我给它的链接有更多选项,我们推荐使用服务帐户


I want to implement Google BigQuery API so I can execute query from my PHP code in BigQuery.

First I have installed the client library by following command:

composer require google/cloud

Second I have installed the Google Cloud SDK by following command:

curl https://sdk.cloud.google.com | bash

Then I run this command to create the credential:

gcloud beta auth application-default login

All the process is success and after run credential request I get the following message:

Credentials saved to file: 

[/home/some/my/dir/application_default_credentials.json]

These credentials will be used by any library that requests
Application Default Credentials.

Then I want to run this code on PHP:

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;

# Your Google Cloud Platform project ID
$projectId = 'PROJECT ID';

# Instantiates a client
$bigquery = new BigQueryClient([
    'projectId' => $projectId
]);

# The name for the new dataset
$datasetName = 'my_new_dataset';

# Creates the new dataset
$dataset = $bigquery->createDataset($datasetName);

echo 'Dataset ' . $dataset->id() . ' created.';

But unfortunately I got following message error:

Fatal error: Uncaught exception 'Google\Cloud\Exception\ServiceException' with message 'Could not load the default credentials

So my question is: whats wrong and what must I do?

Thank you

Default credentials are provided by the Google APIs Client Library for PHP, versions 2.0.0 and newer. To use them, call useApplicationDefaultCredentials:

$client = new Google_Client();
$client->useApplicationDefaultCredentials();

Then, use the credentials to access an API service as follows:

$client->setScopes(['https://www.googleapis.com/auth/books']);
$service = new Google_Service_Books($client);
$results = $service->volumes->listVolumes('Henry David Thoreau');

I am suggesting checking out the link I gave it has much more options and we recommend using service accounts.