Bachelor Tech
  • Home
  • Tutorials
  • Portfolio
  • About Jan
  • Contact Jan

Utilize Composer to talk to Google Sheets API

by Jan Bachelor January 20, 2024
  1. Note down the spreadsheet ID of the document In GSheets that you want to pull data from we will need to know two values when using Composer to query Google Sheets API. For starters, I recommend using a simple two-column GSheet.
Note down the ID of your spreadsheet
  1. Copy paste your service account key into the Composer’s directory. Open the JSON file on your computer and copy its contents. Then via SSH, paste it.
# Go into the directory with Composer (as per previous step)
cd /tmp/composer

# Create a file into which you can paste the contents of the JSON file
nano service_key.json

# Press SHIFT + Insert (or CTRL+V / Command+V) to paste the text, followed by CTRL+X (Command+X) and confirm that you want to save the doc by pressing 'Y' and enter.
  1. Let us now create a simple a .php document that test that we can connect and pull the data.
# Go into the directory with Composer (as per previous step)
cd /tmp/composer
nano gsheet.php

# As before Press SHIFT + Insert (or CTRL+V / Command+V) to paste the text
<?php
// Your spreadsheet ID
$spreadsheetID = 'ENTER_THE_GSHEET_ID_HERE';
$range = 'NAME_OF_THE_INDIVIDUAL_SHEET';

// Connect the Google Sheets API client
require_once __DIR__ . '/vendor/autoload.php';

// Our service account access key
$googleAccountKeyFilePath = __DIR__ . '/service_key.json';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $googleAccountKeyFilePath);

// Create new client
$client = new Google_Client();

// Set credentials
$client->useApplicationDefaultCredentials();

// Adding an access area for reading, editing, creating and deleting tables
$client->addScope('https://www.googleapis.com/auth/spreadsheets');

$service = new Google_Service_Sheets($client);

// Get the contents of an entire sheet by its name
$response = $service->spreadsheets_values->get($spreadsheetID, $range);

// output the result
var_dump($response);
?>

# To save + exit, press CTRL+X (Command+X) and confirm that you want to save the doc by pressing 'Y' and enter.

  1. If we were to launch the code now, it would fail because the service account does not have access to the file. You will need to open the spreadsheet and share it with the email address that you created in the first step.
Remember to share the GSheet with the service acccount you created in Google Cloud Console

Note for organizations: if you get an error message that you cannot share the doc outside of your organization, you will need to have your GSuite admin move your GSuite account into an OU that is allowed to share externally.

  1. Execute the code!
php gsheet.php

If you receive error messages related to ‘Could not load default credentials’, then there is formatting issue with the JSON file. Make sure that there are no extra spaces on the line that starts with ‘—–BEGIN PRIVATE KEY—–‘ and the ‘— END PRIVATE KEY’. See below:


Spot for the two areas where extra spaces need to be removed to make the JSON file readable
  1. Check the output. I have highlighted three things that are of particular interest for us:
    • string(4) “ROWS” –> indicates that the sheet is being read as rows – one array per row. In the next step, we will look into how to communicate that we want to just load one column.
    • string(15) “Sheet1!A1:Z1000” –> How the range that we specified was interpreted by GSheet API. In the fuiture step, we will look into specifying a smaller scope to only fetch data that we need. You may wish to consider the structure of your GSheets in relation to the range that you will then need to fetch.
    • [“values”] –> values lead us to an array of arrays – the values that we want to fetch into our Gravity form (or another destination) are coated in another array that we need to go through to extract the actual values we want to get out.
jan@entelechia:/tmp/composer$ php gsheet.php
object(Google_Service_Sheets_ValueRange)#73 (7) {
  ["collection_key":protected]=>
  string(6) "values"
  ["majorDimension"]=>
  string(4) "ROWS"
  ["range"]=>
  string(15) "Sheet1!A1:Z1000"
  ["values"]=>
  array(3) {
    [0]=>
    array(1) {
      [0]=>
      string(5) "Steve"
    }
    [1]=>
    array(1) {
      [0]=>
      string(6) "George"
    }
    [2]=>
    array(1) {
      [0]=>
      string(5) "Lucia"
    }
  }
  ["internal_gapi_mappings":protected]=>
  array(0) {
  }
  ["modelData":protected]=>
  array(0) {
  }
  ["processed":protected]=>
  array(0) {
  }
}

So how do we fetch a specific column or multiple sheets? And how do we get the values into Gravity Forms? Follow to the next step to see 🙂

Sources:

  • Pocket Admin’s blog
  • Artisan’s web blog

Install Composer + Google API Client (Linux)
Use GSheets APIv4 in WordPress using the Code Snippets plugin
Go back to course overview: Dynamically Populate Gravity Forms from Google Sheets (GSheets APIv4) > Part 1 - Get GSheets API working with your WordPress instance

Leave a Comment Cancel Reply

Save my name, email, and website in this browser for the next time I comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 FacebookWhatsappEmail

Course Steps

    1. Create a Google Service Account + Key
    2. Install Composer + Google API Client (Linux)
    3. Utilize Composer to talk to Google Sheets API
    4. Use GSheets APIv4 in WordPress using the Code Snippets plugin
    4 lessons
    1. Example 1a: Purchase orders - load a list of clients into a Gravity Forms dropdown from a GSheet
    2. Example 1b: Purchase orders - load a list of projects from a GSheet based on the previously selected clients into a Gravity Forms dropdown
    2 lessons
Previous Next

Recent Comments

  • Jan Bachelor on Dynamic DNS Set Up with DuckDNS on OPNSenseHi Jake, that's awesome, congratulations on getting…
  • Jake on Dynamic DNS Set Up with DuckDNS on OPNSensefollowed guide above to the T and all is working. i…
  • Fastbrain on Dynamic DNS Set Up with DuckDNS on OPNSenseThanks for the guide. For some reason, after follow…

Other courses

Install iRedMail Mail Server As Proxmox VM With...

October 31, 2024

Remote Bucket Storage for Proxmox VM Backups

August 16, 2024

Concur Alternative: Import Employees’ Credit Card Expenses to...

January 19, 2024

Create an automated Gravity workflow that will allow...

January 19, 2024

Dynamically Populate Gravity Forms from Google Sheets (GSheets...

March 16, 2021
Bachelor Tech
  • Home
  • Tutorials
  • Portfolio
  • About Jan
  • Contact Jan

Recent Posts

  • How to join two Proxmox nodes into a cluster (PVE 8.x)

  • How to Rename a Proxmox Node

  • How to mount an NFS share on an Android box

Facebook Twitter Instagram Pinterest Linkedin Youtube

All Rights Reserved. The theme was customized from Soledad, see PenciDesign