Tag Archives: Drive SDK

VIDEO: Part 1—Introducing Team Drives for developers

Enterprises are always looking for ways to operate more efficiently, and equipping developers with the right tools can make a difference. We launched Team Drives this year to bring the best of what users love about Drive to enterprise teams. We also updated the Google Drive API, so that developers can leverage Team Drives in the apps they build.

In this latest G Suite Dev Show video, we cover how you can leverage the functionality of Team Drives in your apps. The good news is you don’t have to learn a completely new API—Team Drives features are built into the Drive API so you can build on what you already know. Check it out:

By the end of this video, you‘ll be familiar with four basic operations to help you build Team Drives functionality right in your apps:
  1. How to create Team Drives 
  2. How to add members/users to your Team Drives 
  3. How to create folders in Team Drives (just like creating a regular Drive folder) 
  4. How to upload/import files to Team Drives folders (just like uploading files to regular folders) 
The Drive API can help a variety of developers create solutions that work with both Google Drive and Team Drives. Whether you’re an Independent Software Vendor (ISV), System Integrator (SI) or work in IT, there are many ways to use the Drive API to enhance productivity, help your company migrate to G Suite, or build tools to automate workflows.

Team Drives features are available in both Drive API v2 and v3, and more details can be found in the Drive API documentation. We look forward to seeing what you build with Team Drives!

A study on scale: WhatsApp & Google Drive… the story of our integration

Posted by Mike Procopio, Engineering Manager, Google Drive and Wesley Chun, Developer Advocate, Google Apps

WhatsApp is one of the most popular mobile apps in the world. Over a billion users send and receive over 42 billion messages, photos, and videos every day. It's fast, easy to use, and reliable.

But what happens when people lose their phone or otherwise upgrade to a new one? All those messages and memories would be gone. So we worked with WhatsApp to give their users the ability to back up their data to Google Drive and restore it when they setup WhatsApp on a new phone. With messages and media safely stored in your Drive, there’s no more worry about losing any of those memories.

Scaling for a billion users

One of the biggest challenges for an integration of this scope is scaling. How do you back up data for a billion users? Many things were done to ensure the feature works as intended and is unnoticeable by users. Our approach? First, we relied on a proven infrastructure that can handle this kind of volume—Google Drive. Next, we optimized what to back up and when to do the backups—the key was to upload only incremental changes rather than transmit identical files.

On the server side (backend), we focused on optimizing byte storage as well as the number of network calls between WhatsApp and Google. As far as deployment goes, we rolled out slowly over several months to minimize the size and impact of deployment.

WhatsApp & Google Drive, a seamless integration

If you have ever used WhatsApp, you know how it gets out of your way, and lets you get started quickly: no account creation, no passwords to manage, and no user IDs to remember or exchange. This sets a high bar for any integration with WhatsApp: for it to feel like a natural part of WhatsApp, it has to be as seamless, fast, and reliable as WhatsApp itself.

By using the Google Drive API, we were able to achieve this: no need to type in any usernames or passwords, just a few taps in the app, and WhatsApp starts backing up. The best part is that all the tools used in the integration are available to all developers. With the Google Drive API, seamless and scalable integrations are as easy to use for the user as they are for developers.

Are you ready to integrate your web and mobile apps with Google Drive? Get started today by checking out our intro video as well as the video demoing the newest API, then dig in with the developer docs found at developers.google.com/drive. We're excited to see what you build next with the Drive API—and we're ready to scale with you!

A leaner and faster Google Drive API

Posted by Dan McGrath, Product Manager, Google Drive

Today, version 3 (v3) of the Google Drive API is available, providing developers with a leaner, faster by default, and more consistent interface to Google Drive. This latest update is designed to be easier for developers who are integrating with Drive for the first time.

In the time since we launched the original version of the Drive SDK, we’ve learned a lot about how developers are using our API and the pitfalls they’ve encountered. This version simplifies the API in several ways, including:

  • Reducing the number of collections developers need to understand
  • Removing some duplication
  • Cleaning up method and property names to be more consistent
  • Setting defaults that are faster and more efficient

For example, our files.list call now only includes the most commonly used fields that we serve efficiently by default, with additional fields able to be added via the fields parameter. This makes the default call nearly 6X faster in v3 than in v2:

While future versions of the API will be more feature-focused, this release provides improved performance and ease of use over the previous version of the API (v2). We will continue to support both versions so that existing apps using v2 can run without changes (developers don’t have to upgrade). For developers with a v2 app who want to take advantage of the new improvements, we’ve got a handy cheat sheet to help with migration.

To get started using the new version of the API, check out the developer docs; and for any questions, find us with the google-drive-sdk tag on StackOverflow. We look forward to seeing what you’ll build with the new API!

Guest Post: Integrating with Google Drive via a Chrome Web Store App

This post is prepared by Nina Gorbunova, Teamlab Office Marketing Manager

About Teamlab Personal
Teamlab Personal is a suite of online document editors free for individual use. We've recently implemented two way integration with Google Drive and would like to share our experience.

Why Google Drive integration
Many of our users connect Google Drive to Teamlab, and we wanted to reach more by being in the Chrome Web Store. The availability of Google Drive SDK and Google Drive API helped us fit it all together. We thought: if a user can connect a Google Drive account to Teamlab Personal, why not build a return path? In the eyes of users, it is an enhancement of their Drive accounts. They get an opportunity to process documents using high formatting quality in browser and to make one more step away from desktop apps.

Integration goals
From the technical side, here is what we wanted to do:
  • Integrate Teamlab editors and viewers with Google Drive.
  • Provide co-editing opportunities.
  • Enable file conversion and creating new files in the common Office Open XML format.
  • Enable users to login with Google to use Teamlab Personal.
Five steps to achieve two-way integration
  1. We registered with Google’s developer console, added our project and connected the Drive API and Drive SDK to the app.
  2. Then we needed to decide what scopes our app needed to access the Google Drive API. We chose the minimal set, ample for us to access the files to edit without trespassing the user’s privacy (most users are not likely to provide full access to 3rd party apps)

  3. Because we work with traditional office apps, we chose docx, xlsx and pptx formats as default file extensions for our app. We also added secondary formats: ppt, pps, odp, doc, odt, rtf, txt, xls, csv, ods, mht, html, htm, fb2, epub, pdf, djvu.
  4. The current listing for the pre-existing app, we modified the code and added the following to the manifest: "container" : "GOOGLE_DRIVE","api_console_project_id" : "YOUR_APP_ID". Once a user installs Teamlab Personal app from Chrome Web Store, it automatically connects to their Google Drive account.
  5. Finally, Teamlab Personal uses OAuth 2.0 for authorization and file access. The application processes requests for creating and opening files.
How it works
As soon as you've installed Teamlab Personal from the Chrome Web Store, the integration automatically activates. Now, you can choose the Teamlab icon when creating new and editing the existing documents.

If the user selects the Teamlab editor as the default, .docx, .xlsx and .pptx files are opened in Teamlab automatically. For other documents, we create a copy in Office Open XML format which will be saved on Drive alongside the original.

Requests processing at personal.teamlab.com

When a file is opened or created on Google Drive using the Teamlab Personal application, the handler gets the request with the following parameters: "ids" ("folderId" if case of file creation), "action", "userId" and "code". The "code" parameter is used to get the authentication token via OAuth 2.0 protocol (with the help of the request to https://accounts.google.com/o/oauth2/token with the "client_id", "client_secret", "redirect_ur parameters", and the additional "grant_type=authorization_code" parameter from the developer console). The received token is used in the subsequent requests. The "ids" parameter is the file to be opened identifier which is sent to the https://www.googleapis.com/drive/v2/files/ address in JSON format. The returned "mimeType" and "downloadUrl" are used to get the file content. That's all what is needed to open the document file in Office Open XML format (.docx, .xlsx or .pptx) in Teamlab.

Files in other formats are converted to the corresponding Office Open XML format and a copy is saved to the Drive folder prior to opening. In this case the "downloadUrl" is used to get the original file. The file is saved with the help of the POST request to the https://www.googleapis.com/upload/drive/v2/files address. In this request the "ContentType" is set as "multipart/related; boundary=boundary" and the request body contains the file information placed before the main request content.

Request code:

string CreateFile(Stream content, string fileName, string mimeType, string folderId, string accessToken){
var bytes = Encoding.UTF8.GetBytes(
"\r\n--boundary\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{\"title\":\""
+ fileName + "\",\"parents\":[{\"id\":\"" + folderId + "\"}]}"
+ "\r\n--boundary\r\nContent-Type: " + mimeType + "\r\n\r\n");

var tmpStream = new MemoryStream();
tmpStream.Write(bytes, 0, bytes.Length);

bytes = Encoding.UTF8.GetBytes("\r\n--boundary--\r\n");
tmpStream.Write(bytes, 0, bytes.Length);

var request = WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart");
request.Method = "POST";
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.ContentType = "multipart/related; boundary=boundary";
request.ContentLength = tmpStream.Length;

var buffer = new byte[2048];
int readed;
tmpStream.Seek(0, SeekOrigin.Begin);
while ((readed = tmpStream.Read(buffer, 0, 2048)) > 0) {
request.GetRequestStream().Write(buffer, 0, readed);
return request.GetResponse().GetResponseStream();

The "Works with Google Drive" label does its magic indeed. We strongly recommend other developers build a Chrome Web Store app, as the results are clear and valuable. We had a high jump in installs (see the graph below) after we completed our integration. Teamlab Personal website traffic doubled and we received more than enough of users’ feedback – great impact for further development.

Google Chrome Web Store Impressions&Installations Statistics. Launch - April.

About the author
Nina started her career at Teamlab in 2011 as an intern. She is now a Senior Marketing Manager at Teamlab Office.

Get coding fast with Code School and the Google Drive API

The most challenging part of learning anything new is often simply getting started. Unfortunately, when it comes to programming, the first few minutes (or more!) are often occupied with cumbersome details such as setting up an environment, which results in very little time spent actually writing code. We were certain there must be a better way.

Code School has been doing exciting things with learning to program online. This is why we decided to team up with them to create a way for developers to learn to use the Google Drive API, with no setup required. In the Discover Drive course, you can learn at your own pace from your web browser. You’ll spend less time fussing with coding environments and more time writing code.

To find out what the course is all about, go check it out at Code School. Happy coding!

Cross-posted on the Google Developers Blog.

Greg Knoke Google+

Greg Knoke is a technical writer in the Google Drive Developer Relations Team. Prior to joining Google, he worked as a scientist developing image and signal processing algorithms. His current interests include new technologies, content management, information architecture, cooking, music, and photography.

Building an Enterprise File Server on Google Drive

Editor's note: This is a guest post by Thomas Gerber. Thomas is the CTO of Altirnao, the developer of the AODocs document management app on the Google Apps Marketplace. Thomas tells the story of his application and provides some tips for developers considering integrating with Google Apps and launching on the Marketplace. — Arun Nagarajan

Google Drive is increasingly popular in the enterprise, and many organizations would like to leverage it as a replacement for their existing on-premises file servers. Moving physical file servers to Drive provides many benefits, such as reliability, cost-effectiveness and the ability to access the files from anywhere and any device. However, the storage structure of Google Drive, where files are owned by many different users, is significantly different from the centralized organization of a file server, where everything is under the control of a small number of system administrators.

To address this problem, AODocs uses the Google Drive API to automatically transfer the ownership of files to a system account, and thus create a sort of “managed area” within Google Drive. With the Google Drive API, AODocs has complete control over the folder structure and the permissions of files owned by this system account. AODocs can be deployed in one click from the Google Apps Marketplace, which makes our application visible (and easy to try out!) for every Google Apps administrator in the world.

Companies who want to store their files on Google Drive may be concerned about losing control of their data (e.g. access to files being lost when an employee leaves the company) and controlling sharing permissions.

AODocs uses a single system account (i.e. a Google Apps account belonging to the customer’s domain, but not used by any human person) as a “proxy” to control the files. When a Google Drive files is added to an AODocs library, the ownership of the file is transferred to the AODocs system account and the file’s writersCanShare attribute is set to false, so that only AODocs is able to modify the file’s permissions afterwards.

To change the ownership of the file, we check if the system account can already access the file, and then either insert a new “owner” permission on it or use the Permissions.update method with the transferOwnership flag:

public void changeOwner(String user, String fileId, String newOwner) {
// Find what is the current permission of the new owner on the file
Permission newOwnerPermission = null;
PermissionList permissionList = RetriableTask.execute(new DrivePermissionListTask(drive.permissions().list(fileId)));
newOwnerPermission = findPermission(permissionList, newOwner);

if (newOwnerPermission == null) {
// New owner is not in the list, we need to insert it
newOwnerPermission = new Permission();
Drive.Permissions.Insert insert = drive.permissions().insert(fileId, newOwnerPermission);
RetriableTask.execute(new DrivePermissionInsertTask(insert));
} else {
// New owner is already in the list, update the existing permission
Drive.Permissions.Update update = drive.permissions().update(fileId, newOwnerPermission.getId(), newOwnerPermission);
RetriableTask.execute(new DrivePermissionUpdateTask(update));

Since all the files are owned by the system account, AODocs completely controls the lifecycle of the file (how they are created, in which folder they are located, who can change their permissions, who can delete them, etc). AODocs can thus provide higher-level document management features on top of Google Drive, such as configuring the retention time of deleted files, limiting external sharing to a whitelist of “trusted external domains”, or recording an audit log of file modifications.

As illustrated in the code snippet above, AODocs relies on the Google Drive API to perform all the operations on the managed files. The main challenge we had when using the Drive API was to properly handle all the error codes returned by the API calls, and make sure we make the difference between fatal errors that should not be tried again (for example, permission denied on a file) and the temporary errors that should be re-tried later (for example, “rate limit exceeded”). To handle that, we have encapsulated all our Google Drive API calls (we are using the Java client library) into a class named RetriableTask, which is responsible for handling the non-fatal errors and automatically retry the API calls with the proper exponential back-off. Here is a simplified version:

public class RetriableTask implements Callable {
private final Callable task;

@Override public T call() {
T result = null;
try {
startTime = System.currentTimeMillis();
result = task.call();
} catch (NonFatalErrorException e) {
if (numberOfTriesLeft > 0) {
// Wait some time, using exponential back-off in case of multiple attempts

// Try again
result = call();
} else {
// Too many failed attempts: now this is a fatal error
throw new RetryException();
} catch (FatalErrorException e) {
// This one should not be retried
return result;

AODocs is designed to work seamlessly with Google Drive, and our top priority is to leverage all the integration possibilities offered by the Google APIs. We are very excited to see that new features are added very often in the Admin SDK, the Google+ API, the Drive API that will allow AODocs to provide more options to system administrators and improve the experience for our end users.

Thomas Gerber profile

Thomas is the CTO of Altirnao. Before founding Altirnao, Thomas has led a team of senior technologists and architects on High Availability/High Performance implementations of enterprise software.

Introducing the Google Drive Android API

Author PhotoBy Magnus Hyttsten, Developer Advocate, Google Drive

With today's developer preview of the Google Drive Android API in Google Play Services 4.1, you can add the convenience of Google Drive cloud storage to your apps without breaking a sweat.

While Drive integration on Android was possible in the past, the new API creates a faster, seamless experience that enables your apps to integrate with the Drive backend within minutes.

The new API offers a number of benefits:

1. Transparent use and syncing of local storage

The Google Drive Android API temporarily uses a local data store in case the device is not connected to a network. So, no need to worry about failed API calls in your app because the user is offline or experiencing a network connectivity problem. Data stored locally in this fashion will automatically and transparently be stored in the Google Drive cloud by Android’s sync scheduler when connectivity is available to minimize impact on battery life, bandwidth, and other resources.

2. Designed for Android and available everywhere

The API was developed for Android and conforms to the latest Android design paradigms, such as using the new uniform client API GoogleAPIClient. And being part of the latest release of Google Play Services provides additional benefits:
  • There’s minimal impact on the weight of your apps. As the client library is a stub to Google Play Services, incorporating the API has minimal impact on the size of your .apk binaries, resulting in faster downloads, fewer updates, and smaller execution footprint.
  • User files are automatically synced between different devices (provided the app has the same namespace and is signed with the same key).
  • Any device running the Gingerbread or later releases of Android and Google Play Services will automatically have support for the Google Drive Android API.

3. User interface components

File picker and creator user interface components are provided with this initial release of the Google Drive Android API, enabling users to select files and folders in Google Drive.

For example, the file picker is implemented as an Intent and allows you develop a native Android user experience with just a couple lines of code. This following code snippet launches the picker and allows the user to select a text file:
// Launch user interface and allow user to select file
IntentSender i = Drive.DriveApi
.setMimeType(new String[] { “text/plain” })
startIntentSenderForResult(i, REQ_CODE_OPEN, null, 0, 0, 0);

The result is provided in the onActivityResult callback as usual.

4. Direct access to Drive functionality

You may be wondering how the Google Drive Android API relates to the Storage Access Framework released as part of Android 4.4 KitKat.

The Storage Access Framework is a generic client API that works with multiple storage providers, including cloud-based and local file systems. While apps can use files stored on Google Drive using this generic framework, the Google Drive API offers specialized functionality for interacting with files stored on Google Drive — including access to metadata and sharing features.

Additionally, as part of Google Play services the Google Drive APIs are supported on devices running Android 2.3 Gingerbread and above.

How to get started

As you incorporate the Google Drive Android API into your apps, we hope it makes your life a little bit easier, and enables you to create fun, powerful apps that take advantage of all that Android and Google Drive can do together.

For more information visit our documentation or explore our API demo and other sample applications on the official Google Drive GitHub repository.

Also check out the official launch video:

Let’s keep the discussions going on +GoogleDrive, and Stack Overflow (google-drive-sdk).

Magnus Hyttsten is a Developer Advocate on the Google Drive team. Beyond work, he enjoys trying out new technologies, thinking about product strategies, and exploring California.

Posted by Scott Knaster, Editor

Cross posted on the Google Developers Blog.

Selecting Upload Destinations with the Picker API

Drive is a great drop zone for incoming files -- no matter if they’re coming from cameras, scanners, faxes, or countless other devices or apps. But throwing files into the root folder makes it difficult for users to find and organize their content.

I’ve seen developers create a folder when the user first connects the app with Drive to keep files organized by the app that created it. It’s a simple technique that is easy to implement and good default behavior for most applications.

With the Picker API, we can go a step further and offer users the choice of destinations too. For example, I’d like my scanner to put work files in one folder and personal files in another, or even configure multiple destinations depending on the type of document I’m scanning.

For this particular use case, the picker needs to be configured to show folders and only show folders. That requires customizing the DocsView just a little.

var docsView = new google.picker.DocsView()

By enabling folders & the ability to select them while simultaneously filtering out everything else, users can quickly and easily select one of their existing folders as a destination. The rest of the code to show the picker is par for the course.

// Handle user actions with the picker.
var callback = function(data) {
if (data.action == google.picker.Action.PICKED) {
var doc = data.docs[0];
alert("You picked " + doc.id);

var picker = new google.picker.PickerBuilder()


Not only is this easy to implement, it’s safer for users. By offloading this functionality to the Picker API, an app only needs the drive.file scope to write files into the user’s preferred location.

You can learn more about the Picker API at developers.google.com or ask questions at StackOverflow with the google-drive-sdk tag.

Steven Bazyl   profile | twitter

Steve is a Developer Advocate for Google Drive and enjoys helping developers build better apps.

Google Drive API Push Notifications

If your app needs to keep up with changes in Drive, whether to sync files, initiate workflows, or just keep users up to date with the latest info, you’re likely familiar with Drive’s changes feed. But periodic polling for changes has always required a delicate balance between resources and timeliness.

Now there’s a better way. With push notifications for the Drive API, periodic polling is no longer necessary. Your app can subscribe for changes to a user’s drive and get notified whenever changes occur.

Suppose your app is hosted on a server with my-host.com domain and push notifications should be delivered to an HTTPS web-hook https://my-host.com/notification:

String subscriptionId = UUID.randomUUID().toString();
Channel request = new Channel()

As long as the subscription is active, Google Drive will trigger a web-hook callback at https://my-host.com/notification. The app can then query the change feed to catch up from the last synchronization point:

changes = service.changes().list()

If your app only needs to be notified about changes to a particular file or folder your app can watch just those files rather than the entire change feed.

If you are interested in using this new feature, please refer to the documentation at developers.google.com. You can see push notifications in action with the Push Notifications Playground and view the source at Github.

Steven Bazyl   profile | twitter

Steve is a Developer Advocate for Google Drive and enjoys helping developers build better apps.

Optimizing Drive API calls

Ever look at the data returned when using the Drive API? A files.list call, even if just returning a single file, can yield upwards of 4kb of data. Drive has a rich set of metadata about files, but chances are your application only needs a small fraction of what’s available.

One of the simplest but most effective optimizations you can make when building apps with the Drive API is limiting the amount of data returned to only those fields needed for your particular use case. The fields query parameter gives you that control, and the results can be dramatic.

A simple example of this is using the files.list call to display a list of files to a user. The naive query, https://www.googleapis.com/drive/v2/files?maxResults=100, generated more than 380kb of data when I ran it against my own corpus. But to render this list nicely, an app only needs a few bits of information -- the document title, icon & thumbnail URLs, the mime type, and of course the file ID.

Using the fields query parameter, the results can be trimmed to just the necessary fields and those needed for fetching subsequent pages of data. The optimized query is https://www.googleapis.com/drive/v2/files?maxResults=100&fields=items(iconLink%2Cid%2Ckind%2CmimeType%2CthumbnailLink%2Ctitle)%2CnextPageToken.

After modifying the query the resulting data was only 30k. That’s more than a 90% reduction in data size! Besides reducing the amount of data on the wire, these hints also enable us to further optimize how queries are processed. Not only is there less data to send, but also less time spent getting it in the first place.

Steven Bazyl   profile | twitter

Steve is a Developer Advocate for Google Drive and enjoys helping developers build better apps.