Google web services have become an essential part of many projects’ infrastructure, a vital integration element. We can no longer imagine online services without them. Meanwhile, Google developers are working on expanding the capabilities of their services, developing new APIs, and increasing the security of our data. Usually, updates are released smoothly for users and do not require any changes on your side. But not this time with the new Google Sheets API.

In 2021, Google introduced version 4 of its Sheets API, which is incompatible with the previous one. This affected data security and privacy. Sheets API v3 support was extended until August 2021 to provide developers with more time to migrate to the new API version. Since the end of support for the v3 API, many JavaScript developers have faced migration issues. And although Google provided a detailed migration guide, as it usually happens, several crucial details are missing from it.

As a support engineer at AnyChart, I have received and continue to deal with numerous requests for help from our JS charting library users who suddenly faced issues with feeding visualizations with data from their Google spreadsheets. It shows the problem has been and remains really topical. So I decided to make a quick Google Sheets API v4 integration guide for anyone else out there.

This article showcases a basic approach to accessing a spreadsheet document on Google Sheets and loading the data from it as apparently the most common use case.

To access a Google Sheets spreadsheet from the JavaScript code, you need google-api-javascript-client and Sheets API, as well as a configured Google project and a document itself. 

Let me walk you through all this step by step.

Configuration on Google Side

1) Create a project

  1. Go to the Google Cloud Platform:
  1. Create a new project:

2) Enable API

  1. Go to “Enable APIS and services”:
Enable API Screen
  1. Type “google sheets” in the search field to find the API:
Google Sheets Search Screen
  1. Select “Google Sheets API”:
  1. Enable the Google Sheets API:
Enable Sheets API Screen

3) Credentials

  1. Go to the “Credentials” tab:
Credentials Screen
  1. Click “Create credentials” and select “API key”:
Create Credentials Screen

Note: Copy and store the API key. You will need it in the JavaScript code later ({GOOGLE_API_KEY} in the JS code). 

c) Click “Restrict key”:

Restrict Key Screen

Note: Keep your API keys secure during both storage and transmission. Best practices for this are well covered by Google in this article. All the code snippets below are simplified for demonstration purposes and do not describe security aspects.

d) In the “Restrict key” dropdown menu, locate the “Google Sheets API” item:

Restrict Key Google Sheets API screen

e) Select it, click “OK” and “SAVE”:

OK screen

4) Create a document

  1. Create a Google Sheets document the way you usually do and fill it with some data. Set a name for the sheet with your data or copy the default one — it will be required later in the JS code ({SHEET_NAME}).
Create Sheet Screen
  1. Enable access to the document via a link. You can do it by clicking on the “Share” button and choosing “Anyone with the link”. (The “Viewer” access is enough.)
Share Sheet Screen
  1. Copy the ID of the document. It can be found in the document’s URL, between the “/spreadsheets/d/” and “/edit” parts. This ID will be required later in the JS code ({SPREADSHEET_ID}).
Copy ID from URL bar

All the necessary settings on the Google side are completed. Let’s move on to an application.

Accessing Google Spreadsheet Data from JavaScript Applications

Now, I will explain how to create a simple JavaScript application that fetches the data from the spreadsheet and shows it to users. To connect the app to the Sheets API, I will use the Google API Client Library for JavaScript (aka gapi), which is well described in its GitHub repository.

1) Creating a basic JavaScript application

First of all, include the gapi library in your page using the direct link.

Add the <table> tag to the HTML code and apply the CSS code you like for the table and its future content.

In the JavaScript code, create a function that will be used for fetching the data.

const start = () => {};

Inside that function, initialize the gapi client with your Google API key created earlier. 

 gapi.client.init({
    'apiKey': '{GOOGLE_API_KEY}',
    'discoveryDocs': ["https://sheets.googleapis.com/$discovery/rest?version=v4"],
  })

Then execute a request to get values via the gapi client. In the request, you should provide the spreadsheet ID and the range of cells where the data you want to access is located.

.then(() => {
    return gapi.client.sheets.spreadsheets.values.get({
      spreadsheetId: '{SPREADSHEET_ID}',
      range: '{SHEET_NAME}!{DATA_RANGE}', 
    })
  })

If all settings are correct, the resolved promise returns a response with the fetched data. Now you can get the data from the response and populate the HTML table using a simple JS script.

.then((response) => {
    
    const loadedData = response.result.values;

    
    const table = document.getElementsByTagName('table')[0];
    
    
    const columnHeaders = document.createElement('tr');
    columnHeaders.innerHTML = `<th>${loadedData[0][0]}</th>
<th>${loadedData[0][1]}</th>`;
    table.appendChild(columnHeaders);

    
    for (let i = 1; i < loadedData.length; i++) {
      const tableRow = document.createElement('tr');
      tableRow.innerHTML = `<td>${loadedData[i][0]}</td>
<td>${loadedData[i][1]}</td>`;
      table.appendChild(tableRow);
    }
  }).catch((err) => {
  	console.log(err.error.message);
  });

To execute the code, call the load() function from the gapi library and pass the function created above as an argument.

gapi.load('client', start);

The resulting application looks like below. You are welcome to check out the full code template of this HTML table with data from Google Sheets on JSFiddle. To get your own thing like this working, just replace {GOOGLE_API_KEY}, {SPREADSHEET_ID}, {SHEET_NAME}, and {DATA_RANGE} with your own information (and don’t keep the braces).

Code View

2) Tinkering output — show the data as a chart

In real-world applications, simple HTML tables are usually not enough; we want to visualize and analyze the data. Let me show you how to create a dashboard that increases the readability of the data and brings us closer to the real-world use case. When I am on duty and asked for assistance with Google Sheets API integration, it is actually the first example I share, and basically, almost always the last as it’s very illustrative and no further help is needed.

So, let’s use the AnyChart JS library for data visualization. It includes column charts and pie charts, which would be enough for this simple dashboard.

Before anything else, add AnyChart’s base JS module to HTML:

<script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-base.min.js"></script>

Also, add <div> tags for dashboard containers and apply a suitable ID for each:

<div id="container1"></div>
<div id="container2"></div>

Most of the JavaScript code remains absolutely the same. I will just rework the code that handles the Sheets API response.

So, keep the first part of the JS code unchanged:

const start = () => {
  
  gapi.client.init({
    'apiKey': '{GOOGLE_API_KEY}',
    'discoveryDocs': ["https://sheets.googleapis.com/$discovery/rest?version=v4"],
  }).then(() => {
    return gapi.client.sheets.spreadsheets.values.get({
      spreadsheetId: '{SPREADSHEET_ID}',
      range: '{SHEET_NAME}!{DATA_RANGE}', 
    })
  }).then((response) => {

In the response handler, parse the data to compose a structure compatible with the AnyChart API:

    const loadedData = response.result.values;
    const parsedData = {
      'header': loadedData.shift(),
      'rows': loadedData,
    };

Now we’ve got everything we need to create and configure charts for the dashboard: 

    
    const columnChart = anychart.column();

    
    columnChart.data(parsedData);

    
    columnChart.title('Sales volume by manager');
    columnChart.xAxis().title('Manager');
    columnChart.yAxis().title('Sales volume, $');

    
    columnChart.container('container1').draw();

    
    const pieChart = anychart.pie(parsedData);
    pieChart.title('Sales volume distribution in the department');
    pieChart.legend().itemsLayout('vertical').position('right');
    pieChart.container('container2').draw();

Then goes the same ending part as with the HTML table — let’s recall it just in case:

  }).catch((err) => {
  	console.log(err.error.message);
  });
};


gapi.load('client', start);

Below is what the resulting dashboard looks like. You can check out the full template code of this dashboard visualizing data from Google Sheets using the v4 API on JSFiddle. To get your own project like this, simply put your own information in place of {GOOGLE_API_KEY}, {SPREADSHEET_ID}, {SHEET_NAME}, and {DATA_RANGE} (and don’t keep the braces).

Dashboard Screen

I hope this article will be helpful to anyone who decides to build an app that uses data from Google Sheets and access it from JavaScript applications. If you have any further questions, please feel free to get in touch with me and I will be happy to do my best to help you out.

For your convenience, here is a list of all useful links from this article, in one place:

Prerequisites

Integration examples



Source link

Translate »