Tag Archives: Google Sheets API

Automate & Extend with Apps Script (Google Cloud for Student Developers)

Posted by Wesley Chun (@wescpy), Developer Advocate, Google Cloud


In the previous episode of our new Google Cloud for Student Developers video series, we introduced G Suite REST APIs, showing how to enhance your applications by integrating with Gmail, Drive, Calendar, Docs, Sheets, and Slides. However, not all developers prefer the lower-level style of programming requiring the use of HTTP, OAuth2, and processing the request-response cycle of API usage. Building apps that access Google technologies is open to everyone at any level, not just advanced software engineers.

Enhancing career readiness of non-engineering majors helps make our services more inclusive and helps democratize API functionality to a broader audience. For the budding data scientist, business analyst, DevOps staff, or other technical professionals who don't code every day as part of their profession, Google Apps Script was made just for you. Rather than thinking about development stacks, HTTP, or authorization, you access Google APIs with objects.

This video blends a standard "Hello World" example with various use cases where Apps Script shines, including cases of automation, add-ons that extend the functionality of G Suite editors like Docs, Sheets, and Slides, accessing other Google or online services, and custom functions for Google Sheets—the ability to add new spreadsheet functions.

One featured example demonstrates the power to reach multiple Google technologies in an expressive way: lots of work, not much code. What may surprise readers is that this entire app, written by a colleague years ago, is comprised of just 4 lines of code:

function sendMap() {
var sheet = SpreadsheetApp.getActiveSheet();
var address = sheet.getRange('A1').getValue();
var map = Maps.newStaticMap().addMarker(address);
GmailApp.sendEmail('[email protected]',
'Map', 'See below.', {attachments:[map]});
}

Apps Script shields its users from the complexities of authorization and "API service endpoints." Developers only need an object to interface with a service; in this case, SpreadsheetApp to access Google Sheets, and similarly, Maps for Google Maps plus GmailApp for Gmail. Viewers can build this sample line-by-line with its corresponding codelab (a self-paced, hands-on tutorial). This example helps student (and professional) developers...

  1. Build something useful that can be extended into much more
  2. Learn how to accomplish several tasks without a lot of code
  3. Imagine what else is possible with G Suite developer tools

For further exploration, check out this video as well as this one which introduces Apps Script and presents the same code sample with more details. (Note the second video emails the map's link, but the app has been updated to attach it instead; the code has been updated everywhere else.) You may also access the code at its open source repository. If that's not enough, learn about other ways you can use Apps Script from its video library. Finally, stay tuned for the next pair of episodes which will cover full sample apps, one with G Suite REST APIs, and another with Apps Script.

We look forward to seeing what you build with Google Cloud.

Google Cloud for Student Developers: Accessing G Suite REST APIs

Posted by Wesley Chun (@wescpy), Developer Advocate, Google Cloud

Recently, we introduced the "Google Cloud for Student Developers" video series to encourage students majoring in STEM fields to gain development experience using industry APIs (application programming interfaces) for career readiness. That first episode provided an overview of the G Suite developer landscape while this episode dives deeper, introducing G Suite's HTTP-based RESTful APIs, starting with Google Drive.

The first code sample has a corresponding codelab (a self-paced, hands-on tutorial) where you can build a simple Python script that displays the first 100 files or folders in your Google Drive. The codelab helps student (and professional) developers...

  1. Realize it is something that they can accomplish
  2. Learn how to create this solution without many lines of code
  3. See what’s possible with Google Cloud APIs

While everyone is familiar with using Google Drive and its web interface, many more doors are opened when you can code Google Drive. Check this blog post and video for a more comprehensive code walkthrough as well as access the code at its open source repository. What may surprise readers is that the entire app can be boiled down to just these 3-4 lines of code (everything else is either boilerplate or security):

    DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
files = DRIVE.files().list().execute().get('files', [])
for f in files:
print(f['name'], f['mimeType'])

Once an "API service endpoint" to Google Drive is successfully created, calling the list() method in Drive's files() collection is all that's needed. By default, files().list() returns the first 100 files/folders—you can set the pageSize parameter for a different amount returned.

The video provides additional ideas of what else is possible by showing you examples of using the Google Docs, Sheets, and Slides APIs, and those APIs will be accessed in a way similar to what you saw for Drive earlier. You'll also hear about what resources are available for each API, such as documentation, code samples, and links to support pages.

If you wish to further explore coding with G Suite REST APIs, check out some additional videos for the Drive, Sheets, Gmail, Calendar, and Slides APIs. Stay tuned for the next episode which highlights the higher-level Google Apps Script developer platform.

We look forward to seeing what you build with Google Cloud!

Mail merge with the Google Docs API

Posted by Wesley Chun, Developer Advocate, Google Cloud

Students and working professionals use Google Docs every day to help enhance their productivity and collaboration. The ability to easily share a document and simultaneously edit it together are some of our users' favorite product features. However, many small businesses, corporations, and educational institutions often find themselves needing to automatically generate a wide variety of documents, ranging from form letters to customer invoices, legal paperwork, news feeds, data processing error logs, and internally-generated documents for the corporate CMS (content management system).

Mail merge is the process of taking a master template document along with a data source and "merging" them together. This process makes multiple copies of the master template file and customizes each copy with corresponding data of distinct records from the source. These copies can then be "mailed," whether by postal service or electronically. Using mail merge to produce these copies at volume without human labor has long been a killer app since word processors and databases were invented, and now, you can do it in the cloud with G Suite APIs!

While the Document Service in Google Apps Script has enabled the creation of Google Docs scripts and Docs Add-ons like GFormit (for Google Forms automation), use of Document Service requires developers to operate within the Apps Script ecosystem, possibly a non-starter for more custom development environments. Programmatic access to Google Docs via an HTTP-based REST API wasn't possible until the launch of the Google Docs API earlier this year. This release has now made building custom mail merge applications easier than ever!

Today's technical overview video walks developers through the concept and flow of mail merge operations using the Docs, Sheets, Drive, and Gmail APIs. Armed with this knowledge, developers can dig deeper and access a fully-working sample application (Python), or just skip it and go straight to its open source repo. We invite you to check out the Docs API documentation as well as the API overview page for more information including Quickstart samples in a variety of languages. We hope these resources enable you to develop your own custom mail merge solution in no time!

Code that final mile: from big data analysis to slide presentation

Posted by Wesley Chun (@wescpy), Developer Advocate, Google Cloud

Google Cloud Platform (GCP) provides infrastructure, serverless products, and APIs that help you build, innovate, and scale. G Suite provides a collection of productivity tools, developer APIs, extensibility frameworks and low-code platforms that let you integrate with G Suite applications, data, and users. While each solution is compelling on its own, users can get more power and flexibility by leveraging both together.

In the latest episode of the G Suite Dev Show, I'll show you one example of how you can take advantage of powerful GCP tools right from G Suite applications. BigQuery, for example, can help you surface valuable insight from massive amounts of data. However, regardless of "the tech" you use, you still have to justify and present your findings to management, right? You've already completed the big data analysis part, so why not go that final mile and tap into G Suite for its strengths? In the sample app covered in the video, we show you how to go from big data analysis all the way to an "exec-ready" presentation.

The sample application is meant to give you an idea of what's possible. While the video walks through the code a bit more, let's give all of you a high-level overview here. Google Apps Script is a G Suite serverless development platform that provides straightforward access to G Suite APIs as well as some GCP tools such as BigQuery. The first part of our app, the runQuery() function, issues a query to BigQuery from Apps Script then connects to Google Sheets to store the results into a new Sheet (note we left out CONSTANT variable definitions for brevity):

function runQuery() {
// make BigQuery request
var request = {query: BQ_QUERY};
var queryResults = BigQuery.Jobs.query(request, PROJECT_ID);
var jobId = queryResults.jobReference.jobId;
queryResults = BigQuery.Jobs.getQueryResults(PROJECT_ID, jobId);
var rows = queryResults.rows;

// put results into a 2D array
var data = new Array(rows.length);
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j] = cols[j].v;
}
}

// put array data into new Sheet
var spreadsheet = SpreadsheetApp.create(QUERY_NAME);
var sheet = spreadsheet.getActiveSheet();
var headers = queryResults.schema.fields;
sheet.appendRow(headers); // header row
sheet.getRange(START_ROW, START_COL,
rows.length, headers.length).setValues(data);

// return Sheet object for later use
return spreadsheet;
}

It returns a handle to the new Google Sheet which we can then pass on to the next component: using Google Sheets to generate a Chart from the BigQuery data. Again leaving out the CONSTANTs, we have the 2nd part of our app, the createColumnChart() function:

function createColumnChart(spreadsheet) {
// create & put chart on 1st Sheet
var sheet = spreadsheet.getSheets()[0];
var chart = sheet.newChart()
.setChartType(Charts.ChartType.COLUMN)
.addRange(sheet.getRange(START_CELL + ':' + END_CELL))
.setPosition(START_ROW, START_COL, OFFSET, OFFSET)
.build();
sheet.insertChart(chart);

// return Chart object for later use
return chart;
}

The chart is returned by createColumnChart() so we can use that plus the Sheets object to build the desired slide presentation from Apps Script with Google Slides in the 3rd part of our app, the createSlidePresentation() function:

function createSlidePresentation(spreadsheet, chart) {
// create new deck & add title+subtitle
var deck = SlidesApp.create(QUERY_NAME);
var [title, subtitle] = deck.getSlides()[0].getPageElements();
title.asShape().getText().setText(QUERY_NAME);
subtitle.asShape().getText().setText('via GCP and G Suite APIs:\n' +
'Google Apps Script, BigQuery, Sheets, Slides');

// add new slide and insert empty table
var tableSlide = deck.appendSlide(SlidesApp.PredefinedLayout.BLANK);
var sheetValues = spreadsheet.getSheets()[0].getRange(
START_CELL + ':' + END_CELL).getValues();
var table = tableSlide.insertTable(sheetValues.length, sheetValues[0].length);

// populate table with data in Sheets
for (var i = 0; i < sheetValues.length; i++) {
for (var j = 0; j < sheetValues[0].length; j++) {
table.getCell(i, j).getText().setText(String(sheetValues[i][j]));
}
}

// add new slide and add Sheets chart to it
var chartSlide = deck.appendSlide(SlidesApp.PredefinedLayout.BLANK);
chartSlide.insertSheetsChart(chart);

// return Presentation object for later use
return deck;
}

Finally, we need a driver application that calls all three one after another, the createColumnChart() function:

function createBigQueryPresentation() {
var spreadsheet = runQuery();
var chart = createColumnChart(spreadsheet);
var deck = createSlidePresentation(spreadsheet, chart);
}

We left out some detail in the code above but hope this pseudocode helps kickstart your own project. Seeking a guided tutorial to building this app one step-at-a-time? Do our codelab at g.co/codelabs/bigquery-sheets-slides. Alternatively, go see all the code by hitting our GitHub repo at github.com/googlecodelabs/bigquery-sheets-slides. After executing the app successfully, you'll see the fruits of your big data analysis captured in a presentable way in a Google Slides deck:

This isn't the end of the story as this is just one example of how you can leverage both platforms from Google Cloud. In fact, this was one of two sample apps featured in our Cloud NEXT '18 session this summer exploring interoperability between GCP & G Suite which you can watch here:

Stay tuned as more examples are coming. We hope these videos plus the codelab inspire you to build on your own ideas.

10 must-see G Suite developer sessions at Google Cloud Next ‘18

Posted by Wesley Chun (@wescpy), Developer Advocate, Google Cloud

Google Cloud Next '18 is only a few days away, and this year, there are over 500 sessions covering all aspects of cloud computing, from G Suite to the Google Cloud Platform. This is your chance to learn first-hand how to build custom solutions in G Suite alongside other developers from Independent Software Vendors (ISVs), systems integrators (SIs), and industry enterprises.

G Suite's intelligent productivity apps are secure, smart, and simple to use, so why not integrate your apps with them? If you're planning to attend the event and are wondering which sessions you should check out, here are some sessions to consider:

  • "Power Your Apps with Gmail, Google Drive, Calendar, Sheets, Slides, and More!" on Tuesday, July 24th. Join me as I lead this session that provides a high-level technical overview of the various ways you can build with G Suite. This is a great place to start before attending deeper technical sessions.
  • "Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides and more" on Monday, July 23rd and Friday, July 27th. Join me for one of our half-day bootcamps! Both are identical and bookend the conference—one on Monday and another on Friday, meaning you can do either one and still make it to all the other conference sessions. While named the same as the technical overview above, the bootcamps dive a bit deeper and feature more detailed tech talks on Google Apps Script, the G Suite REST APIs, and App Maker. The three (or more!) hands-on codelabs will leave you with working code that you can start customizing for your own apps on the job! Register today to ensure you get a seat.
  • "Automating G Suite: Apps Script & Sheets Macro Recorder" and "Enhancing the Google Apps Script Developer Experience" both on Tuesday, July 24th. Interested in Google Apps Script, our customized serverless JavaScript runtime used to automate, integrate, and extend G Suite? The first session introduces developers and ITDMs to new features as well as real business use cases while the other dives into recent features that make Apps Script more friendly for the professional developer.
  • "G Suite + GCP: Building Serverless Applications with All of Google Cloud" on Wednesday, July 25th. This session is your chance to attend one of the few hybrid talks that look at how to you can build applications on both the GCP and G Suite platforms. Learn about serverless—a topic that's become more and more popular over the past year—and see examples on both platforms with a pair of demos that showcase how you can take advantage of GCP tools from a G Suite serverless app, and how you can process G Suite data driven by GCP serverless functions. I'm also leading this session and eager to show how you can leverage the strengths of each platform together in the same applications.
  • "Build apps your business needs, with App Maker" and "How to Build Enterprise Workflows with App Maker" on Tuesday, July 24th and Thursday, July 26th, respectively. Google App Maker is a new low-code, development environment that makes it easy to build custom apps for work. It's great for business analysts, technical managers, or data scientists who may not have software engineering resources. With a drag & drop UI, built-in templates, and point-and-click data modeling, App Maker lets you go from idea to app in minutes! Learn all about it with our pair of App Maker talks featuring our Developer Advocate, Chris Schalk.
  • "The Google Docs, Sheets & Slides Ecosystem: Stronger than ever, and growing" and "Building on the Docs Editors: APIs and Apps Script" on Wednesday, July 25th and Thursday, July 26th, respectively. Check out these pair of talks to learn more about how to write apps that integrate with the Google Docs editors (Docs, Sheets, Slides, Forms). The first describes the G Suite productivity tools' growing interoperability in the enterprise with while the second focuses on the different integration options available to developers, either using Google Apps Script or the REST APIs.
  • "Get Productive with Gmail Add-ons" on Tuesday, July 24th. We launched Gmail Add-ons less than a year ago to help developers integrate their apps alongside Gmail. Check out this video I made to help you get up-to-speed on Gmail Add-ons! This session is for developers either new to Gmail Add-ons or want to hear the latest from the Gmail Add-ons and API team.

I look forward to meeting you in person at Next '18. In the meantime, check out the entire session schedule to find out everything it has to offer. Don't forget to swing by our "Meet the Experts" office hours (Tue-Thu), G Suite "Collaboration & Productivity" showcase demos (Tue-Thu), the G Suite Birds-of-a-Feather meetup (Wed), and the Google Apps Script & G Suite Add-ons meetup (just after the BoF on Wed). I'm excited at how we can use "all the tech" to change the world. See you soon!

10 must-see G Suite developer sessions at Google Cloud Next ‘18



Google Cloud Next '18 is less than a week away and this year, there are over 500 sessions, covering all aspects of cloud computing—IaaS, PaaS, and SaaS. This is your chance to hear from experts in artificial intelligence, as well as learn first-hand how to build custom solutions in G Suite alongside developers other Independent Software Vendors (ISVs), systems integrators (SIs) or industry enterprises.

G Suite’s intelligent productivity apps are secure, smart and simple to use, so why not integrate your apps with them? If you’re planning to attend the event and are wondering which sessions you should check out to enhance your skill set, here are some sessions to consider:

  • Power Your Apps with Gmail, Google Drive, Calendar, Sheets, Slides, and More!" on Tuesday, July 24th. Join me as I lead this session that provides a high-level technical overview of the various ways you can build with G Suite. This is a great place to start before attending deeper technical sessions. 
  • “Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides and more” on Monday, July 23rd and Friday, July 27th. If you're already up-to-speed and want to leave NEXT with actual, working code you can use at school or on the job, join us for one of our bootcamps! Both are identical and bookend the conference—one on Monday and another on Friday. While named the same as the technical overview talk above, these dive a bit deeper, show more API usage examples and feature hands-on codelabs. Register today to ensure you get a seat.
  • Automating G Suite: Apps Script & Sheets Macro Recorder” or “Enhancing the Google Apps Script Developer Experience” on Tuesday, July 24th. Interested in Google Apps Script, our customized serverless JavaScript runtime used to automate, integrate, and extend G Suite apps and data? The first session introduces developers and ITDMs to new features as well as real business use cases while the other session dives into recent features that make Apps Script more friendly for the professional developer. 
  • G Suite + GCP: Building Serverless Applications with All of Google Cloud” on Wednesday, July 25th. This session is your chance to attend one of the few hybrid talks that look at how to you can build applications on both GCP and G Suite platforms. Learn about GCP and G Suite serverless products— a topic that’s become more and more popular over the past year—and see how it works firsthand with demos. I’m also leading this session and eager to show how you can leverage both platforms in the same application. 
  • Build apps your business needs, with App Maker” or “How to Build Enterprise Workflows with App Maker” on Tuesday, July 24th and Thursday, July 26th respectively. Google App Maker is a new low-code, development environment that makes it easy to build custom apps for work. It’s great for business analysts, technical managers or data scientists who may not have software engineering resources. With a drag & drop UI, built-in templates, and point-and-click data modeling, App Maker lets you go from idea to app in minutes! Learn all about it with our pair of App Maker talks featuring our Developer Advocate, Chris Schalk. 
  • The Google Docs, Sheets & Slides Ecosystem: Stronger than ever, and growing” or “Building on the Docs Editors: APIs and Apps Script” on Wednesday, July 25th and Thursday, July 26th respectively. Check out these pair of talks to learn more about how to write apps that integrate with Google Docs, Sheets, Slides and Forms. The first describes the G Suite productivity tools' growing interoperability in the enterprise with while the second focuses on the different options available to developers for integrating with the G Suite "editor" applications. 
  • Get Productive with Gmail Add-ons” on Tuesday, July 24th. We launched Gmail Add-ons less than a year ago (You can check out this video to learn more.) to help developers integrate their apps alongside Gmail. Come to this session to learn the latest from the Gmail Add-ons and API team.
I look forward to meeting you in person at Next '18. In the meantime, you can check out the entire session schedule to find out everything NEXT has to offer or this video where I talk about how I think technology will change the world. See you soon!

Hangouts Chat alerts & notifications… with asynchronous messages

Posted by Wesley Chun (@wescpy), Developer Advocate, G Suite

While most chatbots respond to user requests in a synchronous way, there are scenarios when bots don't perform actions based on an explicit user request, such as for alerts or notifications. In today's DevByte video, I'm going to show you how to send messages asynchronously to rooms or direct messages (DMs) in Hangouts Chat, the team collaboration and communication tool in G Suite.

What comes to mind when you think of a bot in a chat room? Perhaps a user wants the last quarter's European sales numbers, or maybe, they want to look up local weather or the next movie showtime. Assuming there's a bot for whatever the request is, a user will either send a direct message (DM) to that bot or @mention the bot from within a chat room. The bot then fields the request (sent to it by the Hangouts Chat service), performs any necessary magic, and responds back to the user in that "space," the generic nomenclature for a room or DM.

Our previous DevByte video for the Hangouts Chat bot framework shows developers what bots and the framework are all about as well as how to build one of these types of bots, in both Python and JavaScript. However, recognize that these bots are responding synchronously to a user request. This doesn't suffice when users want to be notified when a long-running background job has completed, when a late bus or train will be arriving soon, or when one of their servers has just gone down. Recognize that such alerts can come from a bot but also perhaps a monitoring application. In the latest episode of the G Suite Dev Show, learn how to integrate this functionality in either type of application.

From the video, you can see that alerts and notifications are "out-of-band" messages, meaning they can come in at any time. The Hangouts Chat bot framework provides several ways to send asynchronous messages to a room or DM, generically referred to as a "space." The first is the HTTP-based REST API. The other way is using what are known as "incoming webhooks."

The REST API is used by bots to send messages into a space. Since a bot will never be a human user, a Google service account is required. Once you create a service account for your Hangouts Chat bot in the developers console, you can download its credentials needed to communicate with the API. Below is a short Python sample snippet that uses the API to send a message asynchronously to a space.

from apiclient import discovery
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = 'https://www.googleapis.com/auth/chat.bot'
creds = ServiceAccountCredentials.from_json_keyfile_name(
'svc_acct.json', SCOPES)
CHAT = discovery.build('chat', 'v1', http=creds.authorize(Http()))

room = 'spaces/<ROOM-or-DM>'
message = {'text': 'Hello world!'}
CHAT.spaces().messages().create(parent=room, body=message).execute()

The alternative to using the API with services accounts is the concept of incoming webhooks. Webhooks are a quick and easy way to send messages into any room or DM without configuring a full bot, i.e., monitoring apps. Webhooks also allow you to integrate your custom workflows, such as when a new customer is added to the corporate CRM (customer relationship management system), as well as others mentioned above. Below is a Python snippet that uses an incoming webhook to communicate into a space asynchronously.

import requests
import json

URL = 'https://chat.googleapis.com/...&thread_key=T12345'
message = {'text': 'Hello world!'}
requests.post(URL, data = json.dumps(message))

Since incoming webhooks are merely endpoints you HTTP POST to, you can even use curl to send a message to a Hangouts Chat space from the command-line:

curl \
-X POST \
-H 'Content-Type: application/json' \
'https://chat.googleapis.com/...&thread_key=T12345' \
-d '{"text": "Hello!"}'

To get started, take a look at the Hangouts Chat developer documentation, especially the specific pages linked to above. We hope this video helps you take your bot development skills to the next level by showing you how to send messages to the Hangouts Chat service asynchronously.

Using field masks with update requests to Google APIs

Originally posted on the G Suite Developers Blog
Posted by Wesley Chun (@wescpy), Developer Advocate, G Suite

We recently demonstrated how to use field masks to limit the amount of data that comes back via response payloads from read (GET) calls to Google APIs. Today, we'll focus on a different use case for field masks: update requests.

In this scenario, field masks serve a different, but similar purpose—they still filter, but function more like bitmasks by controlling which API fields to update. The following video walks through several examples of update field mask usage with both the Google Sheets and Slides APIs. Check it out.


In the sample JSON payload below, note the request to set the cells’ bold attribute to true (per the cell directive below), then notice that the field mask (fields) practically mirrors the request:

{
"repeatCell": {
"range": {
"endRowIndex": 1
},
"cell": {
"userEnteredFormat": {
"textFormat": {
"bold": true
}
}
},
"fields": "userEnteredFormat/textFormat/bold",
}
}

Now, you might think, "is that redundant?" Above, we highlighted that it takes two parts: 1) the request provides the data for the desired changes, and 2) the field mask states what should be updated, such as the userEnteredFormat/textFormat/bold attribute for all the cells in the first row. To more clearly illustrate this, let's add something else to the mask like italics so that it has both bold and italic fields:

        "fields": "userEnteredFormat/textFormat(bold,italic)"
However, while both elements are in the field mask, we've only provided the update data for bold. There's no data for italic setting specified in the request body. In this case, italics for all cells will be reset, meaning if the cells were originally italicized, those italics will be removed after this API request completes. And vice versa, if the cells were not italicized to begin with, they'll stay that way. This feature gives developers the ability to undo or reset any prior settings on affected range of cells. Check out the video for more examples and tips for using field masks for update requests.

To learn more about using field masks for partial response in API payloads, check out this video and the first post in this two-part series. For one of the most comprehensive write-ups on both (read and update) use cases, see the guide in the Google Slides API documentation. Happy field-masking!

Using field masks with update requests to Google APIs



We recently demonstrated how to use field masks to limit the amount of data that comes back via response payloads from read (GET) calls to Google APIs. Today, we’ll focus on a different use case for field masks: update requests.

In this scenario, field masks serve a different, but similar purpose—they still filter, but function more like bitmasks by controlling which API fields to update. The following video walks through several examples of update field mask usage with both the Google Sheets and Slides APIs. Check it out.
2
In the sample JSON payload below, note the request to set the cells' bold attribute to true (per the cell directive below), then notice that the field mask (fields) practically mirrors the request:
{
"repeatCell": {
"range": {
"endRowIndex": 1
},
"cell": {
"userEnteredFormat": {
"textFormat": {
"bold": true
}
}
},
"fields": "userEnteredFormat/textFormat/bold",
}
}
Now, you might think, “is that redundant?” Above, we highlighted that it takes two parts: 1) the request provides the data for the desired changes, and 2) the field mask states what should be updated, such as the userEnteredFormat/textFormat/bold attribute for all the cells in the first row. To more clearly illustrate this, let’s add something else to the mask like italics. Here, the updated field mask now has both bold and italic fields:
"fields": "userEnteredFormat/textFormat(bold,italic)"

However, while both elements are in the field mask, we’ve only provided the update data for bold. There’s no data for italic setting specified in the request body. In this case, for all cells will be reset, meaning if the cells were originally italicized, those italics will be removed after this API request completes. And vice versa, if the cells were not italicized to begin with, they’ll stay that way. This feature gives developers the ability to undo or reset any prior settings on affected range of cells. Check out the video for more examples and tips for using field masks for update requests.

To learn more about using field masks for partial response in API payloads, check out this video and the first post in this two-part series. For one of the most comprehensive write-ups on both (read and update) use cases, see the guide in the Google Slides API documentation.  Happy field-masking!

Using Google Sheets filters in Add-ons with Google Apps Script



Developers using Google Apps Script can now access the richer feature set of the updated Google Sheets API with the recent launch of the Advanced Sheets Service. One key benefit of using an advanced service vs. native Apps Script objects, is that developers can access current API features (without having to wait for native support to come along). For example, the advanced service allows developers to access Sheets filters which make Add-ons more engaging.

Filter functionality 

With the Sheets API, developers can already get filtered rows or set new filters on Sheets data. With the Advanced Sheet Service, developers can now have their Add-ons respect those filters and apply new filters to modify what data is visible in the Sheets UI. Plus, with any of the Apps Script advanced services, you can easily access the Sheets and other Google APIs without using the UrlFetch service nor managing the authorization flow that you’d otherwise have to perform if using the REST API directly. The snippet below will return the indexes of the filtered rows in a given Sheet. Note that it is also possible to retrieve the list of rows hidden manually, using the "hide row" menu item in Google Sheets, as indicated in the API documentation. In the code sample here, we’re only exposing rows hidden by filter.

 function getIndexesOfFilteredRows(ssId, sheetId) {
var hiddenRows = [];

// limit what's returned from the API
var fields = "sheets(data(rowMetadata(hiddenByFilter)),properties/sheetId)";
var sheets = Sheets.Spreadsheets.get(ssId, {fields: fields}).sheets;

for (var i = 0; i < sheets.length; i++) {
if (sheets[i].properties.sheetId == sheetId) {
var data = sheets[i].data;
var rows = data[0].rowMetadata;
for (var j = 0; j < rows.length; j++) {
if (rows[j].hiddenByFilter) hiddenRows.push(j);
}
}
}
return hiddenRows;
The fields parameter in the code snippet limits what's returned in the Sheets API response, requesting only the values that matter to your app. For more information, check out this page in the Sheets API doc or this recent video on field masks.

See how some Add-ons use filtering 

There are a number of Add-ons that use advanced filtering in Sheets. Here are some good examples:
  • Yet Another Mail Merge: this Add-on helps users send email campaigns from a spreadsheet and is built to process only the filtered rows of a Sheet. Let's say you have a list of people who are registered for an event, but you've only accepted some of these registrants and need to send an email confirmation. With Yet Another Mail Merge and the updated API, you can filter out people you don't approve to attend and the Add-ons skips them without sending confirmations.
  • Sankey Snip and Chord Snip: these Add-ons helps users create special chart types that aren't available in the Google Sheets UI. When respecting filters is enabled with these Add-ons, the charts will dynamically visualize filtered data. Check out the example below from the Chord Snip Add-on.
Of course the API also provides the ability to add, update or delete filters on a Sheet. This is useful if you want to quickly display rows with a specific status to your users. One example would be if you built a workflow approval Add-on. You can show the user rows that are waiting for approval. The snippet below applies the requested filter on a given Sheet—the API documentation describes a standard basic filter object:

function setSheetBasicFilter(ssId, BasicFilterSettings) {
//requests is an array of batchrequests, here we only use setBasicFilter
var requests = [
{
"setBasicFilter": {
"filter": BasicFilterSettings
}
}
];
Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId);
}

Yet Another Mail Merge, as many mass-mailing tools do, keeps track of all emails sent, opened and clicked. A tracking report is available in the spreadsheet sidebar, and clicking on the number of emails opened will automatically apply a filter to display only the matching rows—all rows with the status “opened.”

Now, you can determine filters applied in a Sheet directly through the Sheets API or through Apps Script apps and Add-ons using the Advanced Sheets Service, and continue to build the best experience for your users.

About the Authors 

Romain Vialard is a Google Developer Expert. After some years spent as a G Suite consultant, he is now focused on products for G Suite and Google Apps users, including add-ons such as Yet Another Mail Merge and Form Publisher.

Bruce Mcpherson is a Google Developer Expert, an independent consultant, blogger and author of Going GAS, Google Apps Script for Beginners, and Google Apps Script for Developers.