Google Sheet API JavaScript with Node.js: A Complete Setup Tutorial

Author

Reads 1.2K

Black Flat Screen Computer Monitor
Credit: pexels.com, Black Flat Screen Computer Monitor

To set up Google Sheet API with JavaScript and Node.js, you'll need to create a project in the Google Cloud Console. This is where you'll enable the Google Sheets API and create credentials for your project.

First, create a new project in the Google Cloud Console by clicking on the "Select a project" dropdown menu and then clicking on the "New Project" button. Give your project a name, such as "Google Sheet API Tutorial".

Next, navigate to the API Library page and search for the Google Sheets API. Click on the result, then click on the "Enable" button to enable the API for your project.

Getting Started

To get started with using the Google Sheet API in JavaScript, you'll first need to enable it. Enable Google Sheet API by going to API and services under your project and clicking ENABLE APIS AND SERVICES, then enter google sheet api in the searching bar and enable it.

This is a crucial step, as it allows you to access the API's functionality.

The Google Sheet API is now enabled, and you're ready to move forward with integrating it into your JavaScript code.

Authentication

Credit: youtube.com, How to Authenticate Google Sheets API in Discord.js Without a .json File

Authentication is a crucial step in connecting your JavaScript application to the Google Sheets API. To authenticate, you need to sign into the Google API to access its services.

There are several methods to authenticate, including using the Google Developers Console and a third-party package called google-spreadsheet. To use this approach, you need to install google-spreadsheet and require the modules at the top of your file.

The Google Developers Console provides a Quickstart guide for most back-end languages, including Node.js. The guide outlines four steps to follow, which can be summarized as:

  1. Go to the Google Developers Console and navigate to the API section.
  2. Click on “Enable APIs” or “Library” to search and enable the Google Sheets API.
  3. Go to Credentials and select “Create credentials”.
  4. Select “Service Account” and proceed forward by creating this service account.
  5. Under “Role”, select Project > Owner or Editor, depending on what level of access you want to grant.
  6. Select JSON as the Key Type and click “Create” to download a JSON file with your credentials.
  7. Rename this credentials file as client_secret.json and copy it into your working directory.
  8. Grant access to the “client email” in the sheet that you’re working in by clicking “Share” and pasting the email in the field, enabling with “Can edit”.

Alternatively, you can use the OAuth2 with V4 method, which involves using the authorizeGoogleAccess() function to show a content screen for the end user to allow access. This function receives the access token in a callback handler defined in this function.

See what others are reading: Google Colab Access Google Drive

Credit: youtube.com, Control Google Sheets with Node.js / JavaScript (v4 API)

To test whether the code works, you can start working with the API by authenticating and getting the data from the second tab of the identified spreadsheet. Make sure to take a look at the output in the console, which will either log the error or the response object. If you are getting a 403 error, this means that something probably went wrong in setting up the authentication.

Making Requests

Making requests to the Google Sheets API is a crucial step in integrating your spreadsheet data into your JavaScript application. You can make requests directly to the API using HTTP requests, which is arguably the easiest way to access the API via v3.

To use this method, you'll need to publish your spreadsheet and access the designated URL, replacing SPREADSHEET_ID and TAB_NUMBER with the correct information from your sheet. For example, the URL https://spreadsheets.google.com/feeds/cells/1UIV4RkOx8KJK2zQYig0klH5_f8FCOdwIWV8YF2VyF8I/2/public/values?alt=json will return the information from the first image with a JSON depicted in the second.

You can also use the request package in Node to make requests to the API, which can be useful if you're working on a server-side application. To do this, you'll need to install the request package and use the following URL structure: https://spreadsheets.google.com/feeds/cells/SPREADSHEET_ID/TAB_NUMBER/public/values?alt=json.

Install Client Library

People Working on Laptops
Credit: pexels.com, People Working on Laptops

To install the client library, you'll need to follow a few simple steps. If you've already installed the dependencies, you can skip this step altogether.

You'll know you've installed the dependencies correctly if you've completed the earlier steps of this tutorial. If not, make sure to go back and follow the instructions to install them.

The client library is a crucial part of making requests, and installing it correctly will save you a lot of headaches down the line.

HTTP Requests (V3)

Making HTTP requests to access data from a Google spreadsheet is a straightforward process. You can utilize the v3 version of the API, which offers an endpoint that returns all the information in a single JSON by accessing a designated URL.

To get started, go to your spreadsheet and click File → Publish to the Web. This will allow you to select the parts of the document that you want to extract data from. These must be published in order to pull data via this method.

Credit: youtube.com, HTTP Request Methods | GET, POST, PUT, DELETE

The URL structure to access the data is https://spreadsheets.google.com/feeds/cells/SPREADSHEET_ID/TAB_NUMBER/public/values?alt=json. For example, the following URL will return the information from the first image with a JSON depicted in the second: https://spreadsheets.google.com/feeds/cells/1UIV4RkOx8KJK2zQYig0klH5_f8FCOdwIWV8YF2VyF8I/2/public/values?alt=json.

If you remove ?alt=json from the end of the URL, you'll receive the data back as an XML. This is useful if you need to work with the data in a different format.

To make this request via Node, you can utilize the request package. This package was installed at the beginning of this tutorial, and you can find the documentation here. Below is an example of the code that would be run in node at the URL: domain.xyz/v3, rendering the page and passing in the response object that can be used in the test.ejs file.

Here are the key steps to follow when making an HTTP request via v3:

  • Go to your spreadsheet and click File → Publish to the Web
  • Utilize the URL structure to access the data, replacing SPREADSHEET_ID and TAB_NUMBER with the correct information from your sheet
  • Remove ?alt=json from the end of the URL to receive the data back as an XML
  • Use the request package to make the request via Node

Once you've enabled the API, you'll get a client ID and client secret that can later be managed in the API console. For the purposes of this type of authentication, you will only need the credentials.json file which should be saved in your working directory.

Parsing Responses

Credit: youtube.com, Parse CSE JSON Response in Google Sheets

Parsing responses is a crucial step in working with the Google Sheet API in JavaScript. Once you've accessed a Google spreadsheet, the API returns a response that needs to be parsed.

The script reads the response data from the API endpoint and stores it in an array. This array contains the spreadsheet data that will be displayed on the UI.

To parse the response data, the script checks if there are any issues with the response. If something strange occurs, it shows a "No records found" message in the browser.

The script then prepares the output HTML with the spreadsheet data and displays it to the target element. This is where the data is made visible to the user.

Authorization

Authorization is a crucial step in accessing Google Sheets via the Google Sheets API in JavaScript. You need to authenticate and authorize the app to allow accessing Google Sheets.

To authenticate, you'll need to call the authorizeGoogleAccess() function, which shows a content screen for the end user to allow access. This function receives the access token in a callback handler defined in it.

Credit: youtube.com, 𝗦𝗲𝘁𝘂𝗽 𝗚𝗼𝗼𝗴𝗹𝗲 𝗖𝗹𝗼𝘂𝗱 𝗖𝗿𝗲𝗱𝗲𝗻𝘁𝗶𝗮𝗹𝘀 𝗢𝗔𝘂𝘁𝗵 𝟮.𝟬 𝗶𝗻 𝗼𝗿𝗱𝗲𝗿 𝘁𝗼 𝗮𝗰𝗰𝗲𝘀𝘀 𝗚𝗼𝗼𝗴𝗹𝗲 𝗦𝗵𝗲𝗲𝘁𝘀 𝗔𝗣𝗜𝘀 - 𝗣𝗮𝗿𝘁 𝟭

The required scope to access the spreadsheet data includes several options. You can select from the following scopes:

Authorization is a one-time process, but you'll need to refresh the access token periodically to keep your app working smoothly.

Connecting to Express

Connecting the Google Sheets database to Express is the final step in utilizing the database to produce a website/application that uses this information in real time.

Hopefully, the previous sections were helpful in identifying different approaches to connect with, authenticate, and pull data from the Google API.

You should have a few routes set up which pull data that you need from the API, and you're free to use whichever route you choose to pass this data through to the express file.

The data is passed through to the express file via your res.render() call.

Within the express file itself, you can utilize this data through EJS (embedded javascript) tags.

Credit: youtube.com, Unlock the Power of Google Sheets API with Javascript | Step-by-Step Tutorial

These tags allow you to render Javascript in-line or alongside your HTML.

For example, if you were pulling from a batchGet() function which passed data through to the express file as “data” and “rows”, you can use the EJS tags to loop through your data and print it directly to the page.

Once you set up the right database-link, you're free to style the page and add additional functionality, just like any other HTML page, since EJS is essentially HTML with Javascript embedded.

Setup Test

To set up a test Google Sheet, create a blank sheet for testing purposes. Go to Google Sheets and create a blank sheet.

To authorize the service account to use your Google Sheet, click Share on the right. Copy and paste your client email in the JSON file you created earlier.

You'll also need the ID of the Google Sheet you want to handle, which can be found in the URL of the sheet. It looks like this: https://docs.google.com/spreadsheets/d/[your-sheet-id]/edit#gid=0.

Updating and Clearing

Credit: youtube.com, How to update Google Sheets using JavaScript and Node JS - Google Sheets API

You can clear the rows and columns of data in a Google Sheet using the clear method. This will leave the specified range empty.

To clear data, you'll need to use the clear method, which will remove all values from the specified range. The clear method is a straightforward way to start fresh.

After clearing the data, you can update the values in the range using the update method. This method requires an array of arrays, where each inner array represents a row of data.

When updating data, make sure the range is set as desired, as the update method will overwrite any existing values in the range. You can test this by running the application and checking the Google Sheet to see if the values are updated correctly.

If this caught your attention, see: Google Sheet Get Sheet Using Name

Update

Updating data to a Google Sheet is a straightforward process. You can use the update method to write values to a specific range.

Black Flat Screen Computer Monitor
Credit: pexels.com, Black Flat Screen Computer Monitor

To update values, you'll need to use an array of arrays, where each inner array contains the values to be written to a row. The range should be set as desired, and the values will be written in the specified order.

For example, if you have an array with multiple inner arrays, the values will be written from the top row to the bottom row, column by column. This means that the first element of the array will be written from A2 to D2, the second element from A3 to D3, and so on.

Remember, if there are already values in the range, the new values will be overwritten on the old values.

See what others are reading: How to Freeze a Row in Google Sheet

Clear

Clearing data is a straightforward process. We can clear the rows and columns of the data by using the clear method.

You can see the rows and columns are empty in the range specified when you run the application.

JavaScript Basics

Credit: youtube.com, Google Sheets API - JavaScript NodeJS Tutorial

JavaScript Basics are essential for working with the Google Sheet API. JavaScript is used to interact with the Google Sheets API to read and write data.

To use the Google Sheets API with JavaScript, you need to use the generated Client ID and API Key. These are used to authenticate and authorize your application to access the Google Sheets API.

The JavaScript code uses the gapi library to interact with the Google Sheets API. The gapi library is loaded using the gapi.load function, which is called in the GAPILoaded function.

The JavaScript code also uses the google.accounts.oauth2 library to handle authentication and authorization. The ClientToken variable is used to store the client token, which is used to authenticate the user.

Here are the basic JavaScript functions used to interact with the Google Sheets API:

  • intializeGapiClient: Initializes the gapi client with the API key and discovery doc URL.
  • enableButtons: Enables the sign in and sign out buttons when the gapi client and google identity services are loaded.
  • GAPILoaded: Loads the gapi library and calls the intializeGapiClient function.
  • GSILoaded: Loads the google identity services and initializes the client token.
  • GAuth: Signs in the user and requests access to the Google Sheets API.
  • displaySheetData: Retrieves the data from the Google Sheet and displays it in a table.
  • ReloadDataSheet: Reloads the data from the Google Sheet.
  • GAuthSignout: Signs out the user and revokes the access token.

Here are the basic JavaScript variables used to interact with the Google Sheets API:

  • client_id: The Client ID generated in the Google Cloud Console.
  • api_key: The API Key generated in the Google Cloud Console.
  • DISCOVERY_DOC: The URL of the discovery doc for the Google Sheets API.
  • SCOPES: The scope of the Google Sheets API, which is set to "https://www.googleapis.com/auth/spreadsheets.readonly".
  • ClientToken: The client token used to authenticate the user.
  • GAPI_init: A flag indicating whether the gapi client is initialized.
  • GIS_init: A flag indicating whether the google identity services are initialized.
  • dataSheetCard: The HTML element that displays the data from the Google Sheet.
  • signin_btn: The HTML element that displays the sign in button.
  • signout_btn: The HTML element that displays the sign out button.
  • contentTable: The HTML element that displays the table of data from the Google Sheet.

The Source

The source of Google Sheet data is a crucial aspect of working with the Google Sheet API in JavaScript. You can access the source code file created for this tutorial by clicking the Download Button.

The tutorial has come to an end, but you can still download the source code file.

Lamar Smitham

Writer

Lamar Smitham is a seasoned writer with a passion for crafting informative and engaging content. With a keen eye for detail and a knack for simplifying complex topics, Lamar has established himself as a trusted voice in the industry. Lamar's areas of expertise include Microsoft Licensing, where he has written in-depth articles that provide valuable insights for businesses and individuals alike.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.