The Google Sheets API is a RESTful interface that lets you read and modify a
spreadsheet’s data. The most common uses of this API include the following
tasks:
- Create spreadsheets
- Read and write spreadsheet cell values
- Update spreadsheet formatting
- Manage Connected Sheets
Below is a list of common terms used in the Sheets API:
- Spreadsheet
-
The primary object in Google Sheets that can contain multiple sheets, each
with structured information contained in cells. A
Spreadsheet resource represents every spreadsheet and has a
uniquespreadsheetId
value,
containing letters, numbers, hyphens, or underscores. You can find the
spreadsheet ID in a Google Sheets URL:https://docs.google.com/spreadsheets/d/spreadsheetId/edit#gid=0
- Sheet
-
A page or tab within a spreadsheet. A
Sheet resource represents each sheet and has
a unique title and numeric
sheetId
value. You
can find the sheet ID in a Google Sheets URL:https://docs.google.com/spreadsheets/d/aBC-123_xYz/edit#gid=sheetId
- Cell
-
An individual field of text or data within a sheet. Cells are arranged in
rows and columns, and can be grouped as a range of cells. A
CellData resource represents each cell, but
it doesn’t have a unique ID value. Instead, row
and column coordinates identify the cells.- A1 notation
-
A syntax used to define a cell or range of cells with a string that
contains the sheet name plus the starting and ending cell coordinates using
column letters and row numbers. This method is the most common and useful
when referencing an absolute range of cells.Show examples
Sheet1!A1:B2
refers to the first two cells in the top two rows of Sheet1.Sheet1!A:A
refers to all the cells in the first column of Sheet1.Sheet1!1:2
refers to all the cells in the first two rows of Sheet1.Sheet1!A5:A
refers to all the cells of the first column of Sheet 1, from row 5 onward.A1:B2
refers to the first two cells in the top two rows of the first visible sheet.Sheet1
refers to all the cells in Sheet1.'My Custom Sheet'!A:A
refers to all the cells in the first column of a sheet named «My Custom Sheet.» Single quotes are required for sheet names with spaces, special characters, or an alphanumeric combination.'My Custom Sheet'
refers to all the cells in ‘My Custom Sheet’.
Tip: Where possible, use distinct names for the objects within your spreadsheets. For example, A1 refers to the cell A1 in the first visible sheet, whereas ‘A1’ refers to all the cells in a sheet named A1. Similarly, Sheet1 refers to all the cells in Sheet1. However, if there’s a named range titled «Sheet1», then Sheet1 refers to the named range and ‘Sheet1’ refers to the sheet.
- R1C1 notation
-
A syntax used to define a cell or range of cells with a string that
contains the sheet name plus the starting and ending cell coordinates using
row numbers and column numbers. This method is less common than A1 notation, but can be
useful when referencing a range of cells relative to a given cell’s
position.Show examples
Sheet1!R1C1:R2C2
refers to the first two cells in the top two rows of Sheet1.R1C1:R2C2
refers to the first two cells in the top two rows of the first visible sheet.Sheet1!R[3]C[1]
refers to the cell that is three rows below and one column to the right of the current cell.
- Named range
-
A defined cell or range of cells with a custom name to simplify
references throughout an application. A
FilterView resource represents a named range. - Protected range
-
A defined cell or range of cells that cannot be modified. A
ProtectedRange resource represents a protected range.
Next steps
-
To learn about developing with Google Workspace APIs, including handling
authentication and authorization, refer to
Develop on Google Workspace. -
To learn how to configure and run a simple Sheets API app, read the
Quickstarts overview.
Sheet
A sheet in a spreadsheet.
JSON representation |
---|
{ "properties": { object ( |
Fields | |
---|---|
|
SheetProperties The properties of the sheet. |
|
GridData Data in the grid, if this is a grid sheet.
The number of GridData objects returned is dependent on the number of ranges requested on this sheet. For example, if this is representing startRow startColumn
For a DATA_SOURCE |
|
GridRange The ranges that are merged together. |
|
ConditionalFormatRule The conditional format rules in this sheet. |
|
FilterView The filter views in this sheet. |
|
ProtectedRange The protected ranges in this sheet. |
|
BasicFilter The filter on this sheet, if any. |
|
EmbeddedChart The specifications of every chart on this sheet. |
|
BandedRange The banded (alternating colors) ranges on this sheet. |
|
DeveloperMetadata The developer metadata associated with a sheet. |
|
DimensionGroup All row groups on this sheet, ordered by increasing range start index, then by group depth. |
|
DimensionGroup All column groups on this sheet, ordered by increasing range start index, then by group depth. |
|
Slicer The slicers on this sheet. |
SheetProperties
Properties of a sheet.
JSON representation |
---|
{ "sheetId": integer, "title": string, "index": integer, "sheetType": enum ( |
Fields | |
---|---|
|
The ID of the sheet. Must be non-negative. This field cannot be changed once set. |
|
The name of the sheet. |
|
The index of the sheet within the spreadsheet. When adding or updating sheet properties, if this field is excluded then the sheet is added or moved to the end of the sheet list. When updating sheet indices or inserting sheets, movement is considered in «before the move» indexes. For example, if there were 3 sheets (S1, S2, S3) in order to move S1 ahead of S2 the index would have to be set to 2. A sheet index update request is ignored if the requested index is identical to the sheets current index or if the requested new index is equal to the current sheet index + 1. |
|
SheetType
The type of sheet. Defaults to GRID |
|
GridProperties Additional properties of the sheet if this sheet is a grid. (If the sheet is an object sheet, containing a chart or image, then this field will be absent.) When writing it is an error to set any grid properties on non-grid sheets.
If this sheet is a DATA_SOURCE rowCount |
|
True if the sheet is hidden in the UI, false if it’s visible. |
|
Color
The color of the tab in the UI. Deprecated: Use tabColorStyle |
|
ColorStyle
The color of the tab in the UI. If tabColor |
|
True if the sheet is an RTL sheet instead of an LTR sheet. |
|
DataSourceSheetProperties
Output only. If present, the field contains DATA_SOURCE |
SheetType
The kind of sheet.
Enums | |
---|---|
|
Default value, do not use. |
|
The sheet is a grid. |
|
The sheet has no grid and instead has an object like a chart or image. |
|
The sheet connects with an external
and shows the preview of data. |
GridProperties
Properties of a grid.
JSON representation |
---|
{ "rowCount": integer, "columnCount": integer, "frozenRowCount": integer, "frozenColumnCount": integer, "hideGridlines": boolean, "rowGroupControlAfter": boolean, "columnGroupControlAfter": boolean } |
Fields | |
---|---|
|
The number of rows in the grid. |
|
The number of columns in the grid. |
|
The number of rows that are frozen in the grid. |
|
The number of columns that are frozen in the grid. |
|
True if the grid isn’t showing gridlines in the UI. |
|
True if the row grouping control toggle is shown after the group. |
|
True if the column grouping control toggle is shown after the group. |
DataSourceSheetProperties
Additional properties of a
DATA_SOURCE
sheet.
JSON representation |
---|
{ "dataSourceId": string, "columns": [ { object ( |
Fields | |
---|---|
|
ID of the DataSource |
|
DataSourceColumn
The columns displayed on the sheet, corresponding to the values in RowData |
|
DataExecutionStatus The data execution status. |
GridData
Data in the grid, as well as metadata about the dimensions.
JSON representation |
---|
{ "startRow": integer, "startColumn": integer, "rowData": [ { object ( |
Fields | |
---|---|
|
The first row this GridData refers to, zero-based. |
|
The first column this GridData refers to, zero-based. |
|
RowData
The data in the grid, one entry per row, starting with the row in startRow. The values in RowData will correspond to columns starting at startColumn |
|
DimensionProperties
Metadata about the requested rows in the grid, starting with the row in startRow |
|
DimensionProperties
Metadata about the requested columns in the grid, starting with the column in startColumn |
RowData
Data about each cell in a row.
JSON representation |
---|
{
"values": [
{
object (
|
Fields | |
---|---|
|
CellData The values in the row, one per column. |
DimensionProperties
Properties about a dimension.
JSON representation |
---|
{ "hiddenByFilter": boolean, "hiddenByUser": boolean, "pixelSize": integer, "developerMetadata": [ { object ( |
Fields | |
---|---|
|
True if this dimension is being filtered. This field is read-only. |
|
True if this dimension is explicitly hidden. |
|
The height (if a row) or width (if a column) of the dimension in pixels. |
|
DeveloperMetadata The developer metadata associated with a single row or column. |
|
DataSourceColumnReference Output only. If set, this is a column in a data source sheet. |
ConditionalFormatRule
A rule describing a conditional format.
JSON representation |
---|
{ "ranges": [ { object ( |
Fields | |
---|---|
|
GridRange The ranges that are formatted if the condition is true. All the ranges must be on the same grid. |
Union field
. The rule controlling this conditional format, exactly one must be set.
can be only one of the following: |
|
|
BooleanRule The formatting is either «on» or «off» according to the rule. |
|
GradientRule The formatting will vary based on the gradients in the rule. |
BooleanRule
A rule that may or may not match, depending on the condition.
JSON representation |
---|
{ "condition": { object ( |
Fields | |
---|---|
|
BooleanCondition The condition of the rule. If the condition evaluates to true, the format is applied. |
|
CellFormat
The format to apply. Conditional formatting can only apply a subset of formatting: bold italic strikethrough foreground color background color |
GradientRule
A rule that applies a gradient color scale format, based on the interpolation points listed. The format of a cell will vary based on its contents as compared to the values of the interpolation points.
JSON representation |
---|
{ "minpoint": { object ( |
Fields | |
---|---|
|
InterpolationPoint The starting interpolation point. |
|
InterpolationPoint An optional midway interpolation point. |
|
InterpolationPoint The final interpolation point. |
InterpolationPoint
A single interpolation point on a gradient conditional format. These pin the gradient color scale according to the color, type and value chosen.
JSON representation |
---|
{ "color": { object ( |
Fields | |
---|---|
|
Color
The color this interpolation point should use. Deprecated: Use colorStyle |
|
ColorStyle
The color this interpolation point should use. If color |
|
InterpolationPointType How the value should be interpreted. |
|
The value this interpolation point uses. May be a formula. Unused if type MIN MAX |
InterpolationPointType
The kind of interpolation point.
Enums | |
---|---|
|
The default value, do not use. |
|
The interpolation point uses the minimum value in the cells over the range of the conditional format. |
|
The interpolation point uses the maximum value in the cells over the range of the conditional format. |
|
The interpolation point uses exactly the value in
. |
|
The interpolation point is the given percentage over all the cells in the range of the conditional format. This is equivalent to |
|
The interpolation point is the given percentile over all the cells in the range of the conditional format. This is equivalent to
if the value was:
(where errors in the range are ignored when flattening). |
FilterView
A filter view.
JSON representation |
---|
{ "filterViewId": integer, "title": string, "range": { object ( |
Fields | |
---|---|
|
The ID of the filter view. |
|
The name of the filter view. |
|
GridRange The range this filter view covers.
When writing, only one of range namedRangeId |
|
The named range this filter view is backed by, if any.
When writing, only one of range namedRangeId |
|
SortSpec The sort order per column. Later specifications are used when values are equal in the earlier specifications. |
|
FilterCriteria The criteria for showing/hiding values per column. The map’s key is the column index, and the value is the criteria for that column.
This field is deprecated in favor of filterSpecs |
|
FilterSpec The filter criteria for showing/hiding values per column.
Both criteria filterSpecs |
ProtectedRange
A protected range.
JSON representation |
---|
{ "protectedRangeId": integer, "range": { object ( |
Fields | |
---|---|
|
The ID of the protected range. This field is read-only. |
|
GridRange The range that is being protected. The range may be fully unbounded, in which case this is considered a protected sheet.
When writing, only one of range namedRangeId |
|
The named range this protected range is backed by, if any.
When writing, only one of range namedRangeId |
|
The description of this protected range. |
|
True if this protected range will show a warning when editing. Warning-based protection means that every user can edit data in the protected range, except editing will prompt a warning asking the user to confirm the edit.
When writing: if this field is true, then editors |
|
True if the user who requested this protected range can edit the protected area. This field is read-only. |
|
GridRange The list of unprotected ranges within a protected sheet. Unprotected ranges are only supported on protected sheets. |
|
Editors
The users and groups with edit access to the protected range. This field is only visible to users with edit access to the protected range and the document. Editors are not supported with warningOnly |
Editors
The editors of a protected range.
JSON representation |
---|
{ "users": [ string ], "groups": [ string ], "domainUsersCanEdit": boolean } |
Fields | |
---|---|
|
The email addresses of users with edit access to the protected range. |
|
The email addresses of groups with edit access to the protected range. |
|
True if anyone in the document’s domain has edit access to the protected range. Domain protection is only supported on documents within a domain. |
BasicFilter
The default filter associated with a sheet.
JSON representation |
---|
{ "range": { object ( |
Fields | |
---|---|
|
GridRange The range the filter covers. |
|
SortSpec The sort order per column. Later specifications are used when values are equal in the earlier specifications. |
|
FilterCriteria The criteria for showing/hiding values per column. The map’s key is the column index, and the value is the criteria for that column.
This field is deprecated in favor of filterSpecs |
|
FilterSpec The filter criteria per column.
Both criteria filterSpecs |
BandedRange
A banded (alternating colors) range in a sheet.
JSON representation |
---|
{ "bandedRangeId": integer, "range": { object ( |
Fields | |
---|---|
|
The id of the banded range. |
|
GridRange The range over which these properties are applied. |
|
BandingProperties
Properties for row bands. These properties are applied on a row-by-row basis throughout all the rows in the range. At least one of rowProperties columnProperties |
|
BandingProperties
Properties for column bands. These properties are applied on a column- by-column basis throughout all the columns in the range. At least one of rowProperties columnProperties |
BandingProperties
Properties referring a single dimension (either row or column). If both
BandedRange.row_properties
and
BandedRange.column_properties
are set, the fill colors are applied to cells according to the following rules:
-
headerColor
and
footerColor
take priority over band colors. -
firstBandColor
takes priority over
secondBandColor
. -
rowProperties
takes priority over
columnProperties
.
For example, the first row color takes priority over the first column color, but the first column color takes priority over the second row color. Similarly, the row header takes priority over the column header in the top left cell, but the column header takes priority over the first row color if the row header is not set.
JSON representation |
---|
{ "headerColor": { object ( |
Fields | |
---|---|
|
Color
The color of the first row or column. If this field is set, the first row or column is filled with this color and the colors alternate between firstBandColor secondBandColor firstBandColor headerColorStyle |
|
ColorStyle
The color of the first row or column. If this field is set, the first row or column is filled with this color and the colors alternate between firstBandColor secondBandColor firstBandColor headerColor |
|
Color
The first color that is alternating. (Required) Deprecated: Use firstBandColorStyle |
|
ColorStyle
The first color that is alternating. (Required) If firstBandColor |
|
Color
The second color that is alternating. (Required) Deprecated: Use secondBandColorStyle |
|
ColorStyle
The second color that is alternating. (Required) If secondBandColor |
|
Color
The color of the last row or column. If this field is not set, the last row or column is filled with either firstBandColor secondBandColor footerColorStyle |
|
ColorStyle
The color of the last row or column. If this field is not set, the last row or column is filled with either firstBandColor secondBandColor footerColor |
DimensionGroup
A group over an interval of rows or columns on a sheet, which can contain or be contained within other groups. A group can be collapsed or expanded as a unit on the sheet.
JSON representation |
---|
{
"range": {
object (
|
Fields | |
---|---|
|
DimensionRange The range over which this group exists. |
|
The depth of the group, representing how many groups have a range that wholly contains the range of this group. |
|
This field is true if this group is collapsed. A collapsed group remains collapsed if an overlapping group at a shallower depth is expanded. A true value does not imply that all dimensions within the group are hidden, since a dimension’s visibility can change independently from this group property. However, when this property is updated, all dimensions within it are set to hidden if this field is true, or set to visible if this field is false. |
Slicer
A slicer in a sheet.
JSON representation |
---|
{ "slicerId": integer, "spec": { object ( |
Fields | |
---|---|
|
The ID of the slicer. |
|
SlicerSpec The specification of the slicer. |
|
EmbeddedObjectPosition The position of the slicer. Note that slicer can be positioned only on existing sheet. Also, width and height of slicer can be automatically adjusted to keep it within permitted limits. |
SlicerSpec
The specifications of a slicer.
JSON representation |
---|
{ "dataRange": { object ( |
Fields | |
---|---|
|
GridRange The data range of the slicer. |
|
FilterCriteria The filtering criteria of the slicer. |
|
The column index in the data table on which the filter is applied to. |
|
True if the filter should apply to pivot tables. If not set, default to |
|
The title of the slicer. |
|
TextFormat The text format of title in the slicer. The link field is not supported. |
|
Color
The background color of the slicer. Deprecated: Use backgroundColorStyle |
|
ColorStyle
The background color of the slicer. If backgroundColor |
|
HorizontalAlign
The horizontal alignment of title in the slicer. If unspecified, defaults to |
The Google Spreadsheets data API is an extension of the GData API protocol, which you can use to create programs that interact with Google Spreadsheets. The API allows you to query for a list of spreadsheets owned by the currently authenticated user, query for a list of worksheets visible to the authenticated user in a given spreadsheet, and query, insert, update, and delete data in a spreadsheet by either cell or row.
The Google Spreadsheets data API is designed for developers who would like to integrate their applications with Google Spreadsheets. To get started:
http://code.google.com/apis/spreadsheets/
The Google Sheets API enables us to read, write, and update a spreadsheet’s data. We can also use it to render user interfaces (UIs) by fetching data from Google Sheets, which will then serve as a database. The Google Sheets API helps developers import data into spreadsheets and build apps that interact with Google Sheets, maximizing functions and increasing productivity.
In this Google Sheets API tutorial for beginners, you’ll learn how to use the Google Sheets API to perform basic CRUD operations.
Prerequisites for Google Sheets API Tutorial
This tutorial assumes that you have
- a basic understanding of JavaScript and Node.js,
- Node.js and npm installed on your computer,
- a code editor (such as VS Code), and
- a Google account.
Project Setup
To use the Google Sheets API, you need a Google Cloud Platform Project with the API enabled, as well as authorization credentials. To get those, follow the steps below.
Step 1: Create a New Project
First, open the Google Cloud Console, and then create a new project.
Step 2: Enable API and Services
At the top left, click Menu ☰ > APIs and Services > Enabled APIs and Services.
Then click on the + Enable APIs and Services button.
Step 3: Create a Service Account
Now that the API is enabled, it will direct you to a page where you can configure the settings for the API.
In the left sidebar, click on the Credentials tab, and then click the Create Credentials button at the top.
Next, select Service Account in the drop-down menu.
In the next screen, provide the service account details required; then, click Create and Continue.
Click Continue and Done respectively on the next two dialogs.
Now, your newly created service account will be on the credentials page.
Copy the email address of the service account to the clipboard, as we’ll need it later to share the spreadsheet with this account.
You’ll be directed to the next screen, where we’ll create a new key. To do so, click on the Keys tab, and then click on the Add Key button.
Select the Create New Key option, and then the key type of JSON.
Lastly, rename the downloaded JSON file, and move it into your project folder. This keyfile contains the credentials of the service account that we need in our Node.js script to access the spreadsheet from Google Sheets.
How to Use the Google Sheets API
Now that we’re done setting up the project and its credentials in the Google cloud console, let’s explore how to use the basic API functions in Google Sheets.
Create a Spreadsheet
Before diving into the code, head over to Google Sheets and make a new spreadsheet. Enter in some dummy data so that we have something to fetch while testing the API.
Now, let’s add the service account email address and assign it the Editor role, which gives it permission to read, write, update, and delete data.
Click on the Share button in the top-right corner. This will open a modal where we’ll share the spreadsheet with the service account. Make sure to uncheck the Notify people checkbox.
Click the Share button to share the spreadsheet with the service account.
Application Setup
Now that we’re done with the configuration, let’s get into the code. Open up your code editor and create a new project folder. I’ll be using VS Code. You can checkout and run the example application locally via Runme. Otherwise go ahead and follow the tutorial.
Copy and paste the downloaded keyfile into the root of the directory. Rename the file to a simpler one, like keys.json.
Next, navigate to the root of the project, open up the integrated terminal in VS Code, and run this command:
This command will initialize the directory and create an empty package.json file, which defines important information about the project such as dependencies and project version.
Next, let’s install a couple of dependencies:
- Google APIs, to access the Google Sheets API
- Express, to manage the server and routing
- nodemon, for local development so that the server will restart when we save the file
When that is finished installing, run the following code to install nodemon as a dev dependency:
After running the commands, you’ll get a package-lock.json file and the node_modules folder.
Now, to configure nodemon to restart the server on every file save, open up the package.json file and add the following code:
This will enable us to run the dev server using the command npm run dev.
Now, your package.json file should look like this:
Note that the dependency versions may be different.
Integrating the Google Sheets API
Next, create a file named index.js in the project folder. Open the index.js file and import the dependencies we just installed.
Initialize Express and listen for the server. I’m using port 8080, but you can choose any port.
Next, add the following code:
Let’s break the above code into bits:
First, we created a new Google auth object so that we can authorize the API request. This works by passing in the keyFile, which is the keys.json (assuming the file is stored at the root level of the project), and scopes property, which specifies the Google API we’re using.
Second, the authClient variable stores the service account details (client instance) from the getClient() method once the details have been verified in the auth object.
Third, we create an instance of the Google Sheets API. It takes an object with two properties: version (the current version, in our case v4) and auth, the authClient that we created.
Lastly, we return the variables so that we can access the spreadsheet values in any routes of the app.
Reading Data From a Spreadsheet
Now, to get the data from the spreadsheet, we’ll use the sheets.spreadsheets.values.get method, which takes in two required path parameters—spreadsheetId and range—and stores them in a response variable.
We extract the spreadsheetId from the URL of the spreadsheet and store it in a global variable, id:
The text underlined in red is the spreadsheet ID.
While the range defines the range of cells to read from, here we use the spreadsheet name. Every spreadsheet file has at least one sheet, which is identified by the sheet name. In our example, we’re using the sheet name Sheet 1, which you can find at the bottom left of the spreadsheet.
You can also limit the range of the sheet by adding the sheet name, an exclamation symbol, and then the column range (e.g., Sheet1!A1:C5).
The sheets.spreadsheets.values.get method has three other optional query parameters:
- majorDimension defines the major dimension of the values, either rows or columns. The default is ROWS.
- valueRenderOption defines how values should be rendered in the output. The default is FORMATTED_VALUE.
- dateTimeRenderOption defines how dates, times and duration should be rendered in the output. The default is SERIAL_NUMBER.
Now, run the following command in the terminal to start the server:
Then, head over to your browser, and type in http://localhost:8080. The result should be something like this:
If it doesn’t look aligned like this, install JSONVue to format your JSON files in the browser. With this, we’ve successfully read the data from our spreadsheet.
Writing and Updating Data into the Spreadsheet
To append data after a table of data in a sheet, use the sheets.spreadsheets.values.append method, which takes in the spreadsheet ID, the range of cells to write into, the value entered by the user, and the resource object containing the information to insert into the rows.
The valueInputOption property defines how the input data should be interpreted. The values will be parsed according to how the user typed them into the UI.
The resource object has a child, values, which is an array of the data to be added to the sheets. Here, we’re adding a new row with the values for the student name, gender, and class level.
Save the code and head over to Google Sheets, where you’ll find that the new entry has been added. If not, refresh the local server and then go back to Google Sheets.
There’s also the option of using the spreadsheets.values.update request. This enables us to write data to a specified range. For example, the following code will update the class level of Alexandra to «2. Sophomore»:
Deleting Data From Google Sheets
Using the spreadsheets.values.clear method, we can clear values from a spreadsheet. To do that, specify the spreadsheet ID and range. The code below will clear all the values from row A6 to C6:
Updating Spreadsheet Formatting
With the Google Sheets API, we can update the formatting of cells and ranges within spreadsheets.
The following code defines the style for each cell for the range defined. Here, we add a dashed border line with a red color:
This is the resulting layout:
Did you run into trouble getting the examples running? Checkout the full example locally via Runme.
Google Sheets API FAQs
Here are some frequently asked questions about the Google Sheets API.
Can I Use Google Sheets API for Free?
Using the Google Sheets API is free, but each user has usage limits. The Google Sheets API usage limits are quotas and limitations imposed by Google to make sure their API is used fairly and to protect their systems.
However, you may not exhaust this limit unless your app has a lot of users. If you do exceed the limits, you’ll get a 429: Too many requests error. If this happens, try using the exponential backoff algorithm.
How Do I Use APIs in Google Sheets?
Just as you can use the Google Sheets API to read and write Google Sheets, you can also take advantage of its connectivity to use other APIs.
Conclusion
In this tutorial, we’ve explored some basic functions of the Google Sheets API, and you’ve seen how easy it is to set up. But that’s not all. From here, you can make anything simple from a Google Forms clone to a video requests app, or you can use it for something more complex like using it as a database from where an app fetches data and renders it on the front end.
I hope you found this post helpful and insightful. If you want to explore the other functions, check out the documentation.
You can find us at @statefulhq on Twitter or on Discord. Also, if you’re a VS Code user you should checkout
Runme
(transform READMEs into runnable notebooks), and
Marquee (the open source homescreen that helps you stay organized). 👋
Happy coding!
This post was written by Israel Oyetunji. Israel is a frontend developer with a knack for creating engaging UI and interactive experiences. He has proven experience developing consumer-focused websites using HTML, CSS, Javascript, React JS, SASS, and relevant technologies. He loves writing about tech and creating how-to tutorials for developers.
In today’s article, we will learn how to pull cell value from google sheets API. If you don’t know what is google sheets API, and if you don’t have any idea about pulling cell values from google sheets, then don’t worry this article will teach you beginning to advance about how to pull cell value from google sheets API.
What is Google Sheets API?
First, let’s understand what is an API. API is an application programming interface that is developed to interchange the data from two or more unique applications or systems. API helps to get or post data to a third-party web application without accessing sensitive information. APIs are very common today and we have millions of APIs created for different purposes. Today we will talk about google sheets API. Google Sheets API is an amazing platform for google sheets users that help us to get or post data into google sheets. It is offered by the google cloud platform and it’s very easy to use.
You must have a google sheet API project created to use this API, using this API you can easily manipulate your google sheets with the help of google sheet API. Let’s set up us google sheet API to learn how to pull cell value from google sheets API.
Download/Copy Practice Workbook
How to Set up Google Sheets API
Step 1
Go to https://console.cloud.google.com/
Step 2
Select a project or create a new project
Step 3
Name your project and click create.
Step 4
Go to the main menu > marketplace > search sheet API and hit enter
Step 5
Open Google sheets API and click on enable
Step 6
Go to credentials > create credentials
Step 7
Setup API keys
Setup OAuth consent screen
Setup Scope
Add or remove scope > select all > click save and continue
Setup Test users
Don’t add any users, click on back to dashboard
Click on try this API
Go to spreadsheets.values > get
Insert spreadsheetId, range, and other optional parameters.
Rename the google sheets file. For example, I have used “test” here.
Click on execute to get the data from your google sheet file.
How to Get Data from Google Sheets API
Getting data from a spreadsheet from API is no longer a tough job if you know the fundamentals of programming. It’s all about making your functions and connecting with Google sheet API and you can do almost anything programmatically using JavaScript, Python, PHP, and many more programming languages.
Most of us don’t know code and we don’t want to get stuck for this reason. This article is to provide easy tricks and guides to quickly get the result without any prior knowledge of coding; you can get the data from API without getting overwhelmed.
Step 1
Go to console.clound.google.com
Step 2
Go to spreadsheets.values > get
Step 3
Enter sheetId and range to get the data from the spreadsheet using google sheet API. Simple and easy as you like.
Google Sheets API to Find Row by Value
Nothing here.
How to use Google Apps Script to Get Cell Value
Google apps script call values allow you to get the values throughout the google sheet by cell address, or by any means (can be defined in code). We can use it to get the values without an API, it works with the code within the apps script and returns the value on the spreadsheet file.
To begin with Google apps script cell value, firstly you need to have a code that could be written in any language, most preferably it is in JavaScript. You can copy the code to use for free.
Source code to get cell value using Google Sheets API
function onOpen() { var ui = SpreadsheetApp.getUi(); ui.createMenu('GetValues') .addItem('get current', 'getCurrentCellValue') .addItem('get by row col', 'getByRowAndColumn') .addItem('get by address a1', 'getByCellAddressA1Notation') .addToUi(); } function getCurrentCellValue() { var cell = SpreadsheetApp.getActiveSheet().getActiveCell(); var a1 = cell.getA1Notation(); var val = cell.getValue(); SpreadsheetApp.getUi().alert("The active cell "+a1+" value is "+val); } function getByRowAndColumn() { var ui = SpreadsheetApp.getUi(); var response = ui.prompt( 'Cell address', 'Please enter the cell address in this format: row,col for example, 5,2 means row 5 col 2', ui.ButtonSet.OK); var resp_text = response.getResponseText(); var match = resp_text.match(/^(d+),(d+)/); var row = parseInt(match[1]); var col = parseInt(match[2]); var value = SpreadsheetApp.getActiveSheet().getRange(row,col).getValue(); SpreadsheetApp.getUi().alert("The value is "+value); } function getByCellAddressA1Notation() { var ui = SpreadsheetApp.getUi(); var response = ui.prompt( 'Cell address', 'Please enter the cell address (A1 notation)', ui.ButtonSet.OK); var a1 = response.getResponseText(); var value = SpreadsheetApp.getActiveSheet().getRange(a1).getValue(); ui.alert("cell value "+value); }
you can also get the full spreadsheet (the apps script code along with the spreadsheet will be copied)
Here is the spreadsheet
https://docs.google.com/spreadsheets/d/1uLBTlE_-u0PlWDzzLsyPZ5uvytWpNh0oPt5owPWLOPA/copy
These functions are written in JavaScript, they are simply search and return algorithms. We can use them for complex data sets, as its OOP supported, google sheets is cell-oriented, similarly we can use cell orientation to use these functions for complex data sheets even correspondingly on multiple sheets within a google spreadsheet file.
It is safe and easy, go and play around to get familiar with it.
Google Sheets Apps Script to Set Cell Value
You can set values using the google apps script set cell value. This can be done using a small piece of code that is functional and it will set cell values as per cell addresses pointers. Let’s see how it works
Here is the code:
function sheetApp() { // set value to any cell SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet2").getRange('E4').setValue("inserted value") }
It takes call value in A1 notation and a string to pass in that cell.
Code is very simple; you can easily play around and customize it according to your requirements.
Practice the code on your own and you will love it.
This function is very simple, it uses the basic principles of mutation of the data, it works like an array and replace the data by the new data. Similarly, in JavaScript or PHP, if a block scope variable is defined twice then it takes the second value and overwrite the initial value. This function is taking cell address and a string and replace the old value of that cell address, remember if there is no old value, then it will replace the empty space with the new value.
If it is confusing to you? You can leave it, its just for logical definition of the function. Although if you want to add a numeric value, or any other data type that is not string, you can add it using the same method. This code reads the value as string but it will written you any data type that you specify.
Google Sheets Get Cell Value as String
We can use the same get method for google sheets get cell value as string, but in addition, we use a simple concat method to concat our cell data with some text (string) and it makes all the values equal to a string. This is so simple.
=concat(“anystring ” , cellAddress)
Google Sheets API Get Sheet Id
Google sheet Id is an important attribute of any google sheet or spreadsheet. It is a unique value that identifies any google sheet on the internet. We can find the id of any google sheet file from its URL.
Example
https://docs.google.com/spreadsheets/d/1g6GeX6NaKh-sIkUFbYoDqyvuklrn3mfcS–nTnB7r-M/copy
In the above URL, the blue highlighted content is the unique id. For easiness, you can refer to that after /d/ and before /edit content is the id of the spreadsheet.
To recap, we learned how to pull cell values from google sheets API, we have discussed the very basic concept of creating and setting up the first google sheet API to get started. Then we discussed how to get a specific value and how to set a specific cell value. We used Google sheets API and Google Apps Script to achieve all these. It’s very simple, code snippets are available for everyone and the google sheets are also free to use for everyone. Then we discussed how to get your spreadsheet ID. It is very straightforward forward you can get the spreadsheet ID from the URL. Finally, we saw how to get a cell value as a string, this method doesn’t use any script or code. It is a simple formula-based trick to concat an empty string with the original value.
Tutorial: Google Sheets API
Notes
- To get value from google sheets API you need to set up your google sheet API by following the steps described above with screenshots.
- You can python or any other language to do it, but if you are not familiar with coding you can easily use the Google API which provides an easy UI to perform this task.
- Getting cell values is very easy you can use the code provided to use the full functionality of getting call values.
- Similarly, you can set cell values by using the small code of the google apps script. Remember that all these methods are mutable and they will affect your original data.
- Getting call values as string is not a commonly used feature but very helpful when working on website data, you need to convert an input into a string before any operation is performed, here you can use string concatenation, it is a fast and powerful feature that converts any data type into a string.
- To get the google sheet id you can easily copy the link from the spreadsheet URL, In the above URL, the blue highlighted content is the unique id. For easiness, you can refer to that after /d/ and before /edit content is the id of the spreadsheet.
Conclusion
In this article, we learned how to pull cell value from google sheets API. Now google sheets API is a vast topic to cover in one article, so we learned a few techniques and their implementation using google apps script, and google sheets API. After this article, you can easily set up your google sheet API on your own, and you can use it by connecting it with your google cloud console account.
In the beginning, we taught you all the steps to set up google sheets API, then we discussed how to pull cell values from google sheet API, then we discussed several techniques, we saw how to get data from google sheet API, google app script get cell value, and get value, we also saw google sheets get call value as a string, and in last we discussed spreadsheet id, how to get the id of the spreadsheet from the URL, it’s very simple. I described it two times and simplified it for your ease.
Thank you for giving a read to this article, if you like this article, please share it on your social networks and subscribe OfficeDemy blog to get future updates.