Can somebody provide working example of using the Bigquery API with PHP. I see there are examples for python and java but could not find anything for PHP.
Here is the bigquery browser https://bigquery.cloud.google.com/?pli=1
For e.g You can run this SQL in the browser
SELECT corpus,count(*) FROM publicdata:samples.shakespeare
group by corpus limit 5;
I want to simulate similar call via PHP.
Even a rough example of how to use the PHP API will help a lot.
Use the Google API Client for PHP. Here's a simple example of a script that does a single synchronous query job. This uses the class names found in the downloadable API client. Note: the source pulled from SVN features different class names. Note where you must add your own values for client secret, client id, redirect URI, and project id.
<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiBigqueryService.php';
session_start();
$client = new apiClient();
// Visit https://developers.google.com/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('XXXXXXXXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('http://www_your_domain.com/somescript.php');
// Your project id
$project_id = 'XXXXXXXXXXXXXXXXXXXX';
// Instantiate a new BigQuery Client
$bigqueryService = new apiBigqueryService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$client->setAccessToken($client->authenticate());
$_SESSION['access_token'] = $client->getAccessToken();
}
if (isset($_GET['code'])) {
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
?>
<!doctype html>
<html>
<head>
<title>BigQuery API Sample</title>
</head>
<body>
<div id='container'>
<div id='top'><h1>BigQuery API Sample</h1></div>
<div id='main'>
<?php
$query = new QueryRequest();
$query->setQuery('SELECT TOP( title, 10) as title, COUNT(*) as revision_count FROM [publicdata:samples.wikipedia] WHERE wp_namespace = 0;');
$jobs = $bigqueryService->jobs;
$response = $jobs->query($project_id, $query);
// Do something with the BigQuery API $response data
print_r($response);
?>
</div>
</div>
</body>
</html>
The previous answers have outdated code. The following example should work with the more recent API (https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php) :
require_once '../source/application/libraries/Google/autoload.php';
public function createGClient(){
define("CLIENT_ID", "{PROJECT_ID}.apps.googleusercontent.com");
define("SERVICE_ACCOUNT_NAME","{SERVICE_ACCOUNT EMAIL FROM CONSOLE}");
define("KEY_FILE",'../{FILENAME}.p12');
define("PROJECT_ID","{PROJECT_ID}");
define("DATASET_ID","{DATASET_ID}");
define("TABLE_ID","");
$this->client = new Google_Client();
$this->client->setApplicationName("{NAME}");
$key = file_get_contents(KEY_FILE);
$this->client->setAssertionCredentials(new Google_Auth_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/bigquery'), $key, "notasecret"));
$this->client->setClientId(CLIENT_ID);
$this->service = new Google_Service_Bigquery($this->client);
}
public function runQuery(){
// To see the a list of tables
print_r($this->service->tables->listTables(PROJECT_ID, DATASET_ID));
// To see details of a table
print_r($this->service->tables->get(PROJECT_ID, DATASET_ID, TABLE_ID));
// To query a table
$jobs = $this->service->jobs;
$query = new Google_Service_Bigquery_QueryRequest();
$query->setQuery("SELECT * FROM wherever;");
$response = $jobs->query(PROJECT_ID, $query);
print_r($response);
}
This is a modified version of the sample given at: http://michaelheap.com/using-the-php-sdk-with-google-bigquery/ for a service account. To use a client account you would need to use oauth2 and have a pingback address.
I had a lot of issues finding examples.
This is a basic async query, but can demonstrate current PHP API usage, you can see the Python/Java example of the API for async queries here: https://developers.google.com/bigquery/querying-data
Please note, I am not referencing how to setup $client credentials, as it is well documented elsewhere.
$bq = new Google_BigqueryService($client);
//build query
$sql = 'select * from example.table LIMIT 10';
$job = new Google_Job();
$config = new Google_JobConfiguration();
$queryConfig = new Google_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$queryConfig->setQuery($sql);
$insert = new Google_Job($bq->jobs->insert(PROJECT_ID,$job));
$jr = $insert->getJobReference();
$jobId = $jr['jobId'];
$res = new Google_GetQueryResultsResponse($bq->jobs->getQueryResults(PROJECT_ID, $jobId));
//see the results made it as an object ok:
var_dump($results);
/**
* Executes and returns bigQuery response with 'INTERACTIVE' priority
* $this->service is the object of Google_Service_Bigquery
* $this->service = new Google_Service_Bigquery($this->client);
* #param String $sql
* #return Google_Service_Bigquery_GetQueryResultsResponse
*/
public function execute($sql) {
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$queryConfig->setQuery($sql);
/**
* Priority is set to INTERACTIVE for faster response options are 'BATCH'/'INTERACTIVE'
*/
$queryConfig->setPriority("INTERACTIVE");
$config->setQuery($queryConfig);
$job->setId(md5("$sql_{microtime()}"));
$job->setConfiguration($config);
$running = $this->service->jobs->insert('divine-builder-586', $job);
/* #var $running Google_Service_Bigquery_Job */
$jr = $running->getJobReference();
$jobId = $jr['jobId'];
$res = $this->service->jobs->getQueryResults('divine-builder-586', $jobId);
/* #var $res Google_Service_Bigquery_GetQueryResultsResponse */
return $res;
}
Related
I am trying to create an auto-login. I don't want my client to login with credentials for this. I am using this library
https://github.com/aweber/public-api-examples/tree/master/php
Created a credentials.ini file like this
clientId = 'xxx'
clientSecret = 'xxx'
accessToken = 'https://auth.aweber.com/oauth2/token'
redirect_uri = 'http://localhost:8080/php-aweber/'
when I try to access the index.php file, It shows an error like this.
//index.php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
const BASE_URL = 'https://api.aweber.com/1.0/';
// Create a Guzzle client
$client = new GuzzleHttp\Client();
// Load credentials
$credentials = parse_ini_file('credentials.ini');
$accessToken = $credentials['accessToken'];
/**
* Get all of the entries for a collection
*
* #param Client $client HTTP Client used to make a GET request
* #param string $accessToken Access token to pass in as an authorization header
* #param string $url Full URL to make the request
* #return array Every entry in the collection
*/
function getCollection($client, $accessToken, $url) {
$collection = array();
while (isset($url)) {
$request = $client->get($url,
['headers' => ['Authorization' => 'Bearer ' . $accessToken]]
);
$body = $request->getBody();
$page = json_decode($body, true);
$collection = array_merge($page['entries'], $collection);
$url = isset($page['next_collection_link']) ? $page['next_collection_link'] : null;
}
return $collection;
}
// get all of the accounts
$accounts = getCollection($client, $accessToken, BASE_URL . 'accounts');
// get all sharing integration uri's for twitter and facebook
// these are used to create a broadcast that will post to twitter or facebook
// see broadcast example here: https://github.com/aweber/public-api-examples/blob/master/php/create-schedule-broadcast
$integrations = getCollection($client, $accessToken, $accounts[0]['integrations_collection_link']);
echo("Integrations:\n");
foreach ($integrations as $integration) {
if (in_array(strtolower($integration['service_name']), ['twitter', 'facebook'], true)) {
echo "{$integration['service_name']} {$integration['login']} {$integration['self_link']}\n";
}
}
What am I missing or doing wrong?
I tried to run query on Analytics Reporting using the "google/apiclient" and based on example on Google Analytics Reporting v4 documentation. It is returning records, but always only 10. NextPageToken is null in response. Response has only one report. Request has set PageSize for 100 records. I tried many configuration PageSize: 100/500/1000 and PageToken: 1/100/1000/abc and always return only 10 records.
I created the same report on page and it has 1169 pages for 10 records on page (for the same date range).
I looked on limit quotas for API and it has default value.
Did i miss something in code or may be there something problem with configuration service account (some limitation for service account)?
private function getReport($analytics, $VIEW_ID) {
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2020-04-01");
$dateRange->setEndDate("2020-04-12");
$quantityCheckedOut = new Google_Service_AnalyticsReporting_Metric();
$quantityCheckedOut->setExpression("ga:quantityCheckedOut");
$quantityCheckedOut->setAlias("itemQuantity");
$dimension1 = new Google_Service_AnalyticsReporting_Dimension();
$dimension1->setName("ga:productSku");
$pivots = new Google_Service_AnalyticsReporting_Pivot();
$pivots->setDimensions([$dimension1]);
$pivots->setMetrics($quantityCheckedOut);
$order = new Google_Service_AnalyticsReporting_OrderBy();
$order->setFieldName("ga:quantityCheckedOut");
$order->setSortOrder("ASCENDING");
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setPageSize("100");
$request->setHideValueRanges(true);
$request->setMetrics([$quantityCheckedOut]);
$request->setPivots($pivots);
$request->setOrderBys([$order]);
$request->setSamplingLevel("LARGE");
return $request;
}
private function initializeAnalytics()
{
$KEY_FILE_LOCATION = $this->initFolder . '/google.json';
$filesystemAdapter = new Local($this->cacheFolder);
$filesystem = new Filesystem($filesystemAdapter);
$client = new Google_Client();
$client->setApplicationName("App Name");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setIncludeGrantedScopes(true);
$cache = new FilesystemCachePool($filesystem);
$client->setCache($cache);
$client->addScope(Google_Service_AnalyticsReporting::ANALYTICS_READONLY);
$analytics = new Google_Service_AnalyticsReporting($client);
return $analytics;
}
private function printResults($reports)
{
$nextToken = 0;
/** #var Google_Service_AnalyticsReporting_Report $report */
foreach ($reports->getReports() as $report) {
$nextToken = $report->getNextPageToken();
}
return $nextToken
}
public function run(){
/** #var Google_Service_AnalyticsReporting $analytics */
$analytics = $this->initializeAnalytics();
$pageToken = 1;
$i = 0;
$request = $this->getReport($analytics, "VIEW_IDxxxx");
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
while($i < 1) {
$request->setPageToken((string)$i);
$body->setReportRequests($request);
$response = $analytics->reports->batchGet($body);
$pageToken = $this->printResults($response);
$i++;
}
}
It wasn't needed
$pivots = new Google_Service_AnalyticsReporting_Pivot();
$pivots->setDimensions([$dimension1]);
$pivots->setMetrics($quantityCheckedOut);
Instead of that i wrote
$request->setDimensions($dimension1);
Then google response was two columns in data: ProductSKU and itemQuantity. That is i wanted. Somehow Pivot removes nextPageToken and nextPageSize doesn`t affect on request.
I am using Google MyBsiness API for fetching all business reviews.
But I am unable to familer with PHP syntax and GET, POST method use in MYBusiness.
After Oath here are code i am using to fetch review
$mybusinessService = new Google_Service_Mybusiness($client);
$accessToken = file_get_contents($credentialsPath);
$reviews = $mybusinessService->accounts_locations_reviews;
echo '<pre>';print_r($reviews->get('ArtechDev'));exit;
But i am getting error 404 (Fatal error: Uncaught exception 'Google_Service_Exception' with message)
I am sure that I don't know how to pass param and which things needed for it. I am logged in as account which having Location 'ArtechDev' also please
let me know that where can i call
https://mybusiness.googleapis.com/v3/accounts/account_name/locations/location_name/reviews
Thanks
I hope you had found the answer to your question a long time ago, anyway I'll leave this hoping help someone else.
/*$accounts previusly populate*/
/*(GMB - v4)*/
$credentials_f = "google_my_business_credentials_file.json";
$client = new Google_Client();
$client->setApplicationName($aplicattion_name);
$client->setDeveloperKey($developer_key);
$client->setAuthConfig($credentials_f);
$client->setScopes("https://www.googleapis.com/auth/plus.business.manage");
$client->setSubject($accounts->email);
$token = $client->refreshToken($accounts->refresh_token);
$client->authorize();
$locationName = "accounts/#######/locations/########";
$mybusinessService = new Google_Service_Mybusiness($client);
$reviews = $mybusinessService->accounts_locations_reviews;
do{
$listReviewsResponse = $reviews->listAccountsLocationsReviews($locationName, array('pageSize' => 100,
'pageToken' => $listReviewsResponse->nextPageToken));
$reviewsList = $listReviewsResponse->getReviews();
foreach ($reviewsList as $index => $review) {
/*Accesing $review Object
* $review->createTime;
* $review->updateTime;
* $review->starRating;
* $review->reviewer->displayName;
* $review->reviewReply->comment;
* $review->getReviewReply()->getComment();
* $review->getReviewReply()->getUpdateTime();
*/
}
}while($listReviewsResponse->nextPageToken);
$acounts comes from:
$mybusinessService = new Google_Service_MyBusiness(...);
$accounts = $mybusinessService->accounts;
I'm working on a google Calendar sync with my application.
I'm using the latest google-api-php-client
Now I want to update all my event, so i want to use the batch operation.
The example code of the php client api is:
$client = new Google_Client();
$plus = new Google_PlusService($client);
$client->setUseBatch(true);
$batch = new Google_BatchRequest();
$batch->add($plus->people->get(''), 'key1');
$batch->add($plus->people->get('me'), 'key2');
$result = $batch->execute();
So when I "translate" it to the calendar API, I become the following code:
$client = new Google_Client();
$this->service = new Google_CalendarService($client);
$client->setUseBatch(true);
// Make new batch and fill it with 2 events
$batch = new Google_BatchRequest();
$gEvent1 = new Google_event();
$gEvent1->setSummary("Event 1");
$gEvent2 = new Google_event();
$gEvent2->setSummary("Event 2");
$batch->add( $this->service->events->insert('primary', $gEvent1));
$batch->add( $this->service->events->insert('primary', $gEvent2));
$result = $batch->execute();
But when I run this code, I get this error:
Catchable fatal error: Argument 1 passed to Google_BatchRequest::add()
must be an instance of Google_HttpRequest, instance of Google_Event given
And I do not think that "$plus->people->get('')" is a HttpRequest.
Does anybody know what I do wrong, or what method / object I should use to add in the batch?
Or what the correct use of the batch operation for the calendar is?
Thanks in advance!
I had the same problem while working with inserts to the MirrorService api, specifically with timeline items. What is happening is that the the Google_ServiceRequest object is seeing that you've set the useBatch flag on the client and is actually returning returning Google_HttpRequest object before executing the call to Google but the insert statement in the calendar service doesn't properly handle it as such and ends up returning the calendar event object instead.
It also looks like your params to batch->add are backwards. Should be:
$batch->add( $this->service->events->insert($gEvent1, 'primary'));
Here is my modification to the insert method (you'll need to do this in the calendar service with the proper object input to the method). Just a few lines to make it check what class is coming back from the ServiceRequest class:
public function insert(google_TimelineItem $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
if(get_class($data) == 'Google_HttpRequest'){
return $data;
}else{
return new google_TimelineItem($data);
}
} else {
return $data;
}
}
you can use this code to insert events in batch:
public function addEventInBatch($accessToken, $calendarId, array $events)
{
$client = new Google_Client();
$client->setAccessToken($accessToken);
$client->setUseBatch(true);
$service = new Google_Service_Calendar($client);
$batch = $service->createBatch();
collect($events)->each(fn ($event) => $batch->add($service->events->insert($calendarId, $event)));
return $batch->execute();
}
I have been trying to implement a program that uploads backups of my user's websites to google drive. All of them have an account on my domain, so I went through the steps of granting domain wde delegation of authority for my app as described here: https://developers.google.com/drive/delegation
Unfortunately their sample code to instantiate a drive service object fails on many levels. Here it is:
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12';
/**
* Build and returns a Drive service object
* authorized with the service accounts
* that acts on behalf of the given user.
*
* #param userEmail The email of the user.
* #return Google_DriveService service object.
*/
function buildService($userEmail) {
$key = file_get_contents(KEY_FILE);
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),
$key);
$auth->setPrn($userEmail);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
?>
The first obvious error is they have you set up variables but then the function uses constants. So I hardcoded in what should be there for the constants (KEY_FILE, SERVICE_ACCOUNT_EMAIL, etc) just to see if it worked and then I get the following error:
Fatal error: Call to undefined method Google_AssertionCredentials::setPrn()
Does anyone have any suggestions or comments on how to fix this? If you google these issues, google just gives page after page of links to their own documentation, which as I show above, does not work at all.
Basically I was hoping to see an example of how to use a "service account" which has been granted domain wide access to instantiate a drive service object.
It seems that there are some typos (If we wrote the doc, it should be called bug :) ) in the documentation.
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
function buildService($userEmail) {
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key); // Changed!
$auth->prn = $userEmail; // Changed!
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
$service = buildService('email#yourdomain.com');
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = "contents";
$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' =>'text/plain',));
print_r($createdFile);
They defined three varivbales but used three three constants- Removed the contsnts and used the variables instead.
There is no method Google_AssertionCredentials::setPrn(). The property prn's visibility is public. So you can set it as $auth->prn = $userEmail;