Black Friday Sale

How to use Google Drive API and get an API key

If you were planning to start working with Drive API by Google any time soon, we’ve prepared a complete guide for you. Today you’ll learn what exactly it can be used for and also how to get an API key in a few steps.
Share:
Share on Facebook
Share on X
Share on LinkedIn
Share on WhatsApp
Copy Link
How to use Google Drive API and get an API key

What is Google Drive API

Google Drive API is a tool that allows users create apps leveraging Drive cloud storage. By means of this feature you can develop applications integrating with Google Drive and create powerful functionality in your applications.

What can you do using this tool

This option can be used to:

  • Download and upload files to Drive.
  • Search for files and folders .
  • Create complex search queries that return any of the file metadata fields in the Files resource.
  • Allow users share files, folders and drives to cooperate on content.
  • Combine with the Picker API to search all files in Google Drive, return the file name, URL, last modified date, and user.
  • Create shortcuts which are external links to data kept outside of Drive, in a different data store or cloud storage system.
  • Form a dedicated folder to store your application’s data to prevent the app from accessing all the user’s content.
  • Integrate with the Drive UI which can be used to interact with Drive files.

To successfully work with API you’ve got to get an API Key. Let’s see how you can do it. 

How to get Google Drive API key

To generate your API key, your account must be conferred the primitive Editor role on the ongoing project. 

Tip: Roles are used to provide a user, a group or a service account with permissions to use the resource. You can get more information on roles here.

To set up an API key, follow these steps: 

  • Open the APIs & Services → Credentials board in the Cloud Google Drive API console.
Google Cloud Platform console
  • Pick Create credentials option and then select API key from the dropdown list.
Google Cloud Platform console create credentials
  • The dialog screen will demonstrate your new API key.
Google Cloud Platform console get API key

In case you need to state which web pages, IP addresses or applications can apply your API key, you are free to add app restrictions based on your application type. Mind that you can only set one restriction type per API key.

Another way to use APIs – retrieve the data from various platforms. For example, embed Google reviews on your website. This feature is also available in ready-to-use web aplication like Google Reviews widget from Elfsight.

Using Google Drive API: examples

There are several ways you may apply Google Drive API. Let’s discuss some of them.

Example 1: Google Drive API upload file

You can upload file data when you create or update a File resource. There are three types of uploads you can perform:

  • Simple. It is suitable for quick transfer of a small file (5MB or less).
  • Multipart upload. It can be used for a quick transfer of a small file and metadata that describes the file, all in a single request.
  • Resumable upload. It can be performed for more reliable transfer, especially important with large files.

This example demonstrates a simple upload request:

POST googleapis/upload/drive/v3/files?uploadType=media HTTP/1.1
Content-Type: image/jpeg
Content-Length: [NUMBER_OF_BYTES_IN_FILE]
Authorization: Bearer [YOUR_AUTH_TOKEN]

[JPEG_DATA]

A multipart upload request can look like this:

POST googleapis/upload/drive/v3/files?uploadType=multipart HTTP/1.1
Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Type: multipart/related; boundary=foo_bar_baz
Content-Length: [NUMBER_OF_BYTES_IN_ENTIRE_REQUEST_BODY]

--foo_bar_baz
Content-Type: application/json; charset=UTF-8

{
  "name": "myObject"
}

--foo_bar_baz
Content-Type: image/jpeg

[JPEG_DATA]
--foo_bar_baz--

This example displays how to initiate a resumable session to upload a new file:

POST googleapis/upload/drive/v3/files?uploadType=resumable HTTP/1.1
Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: image/jpeg
X-Upload-Content-Length: 2000000

{
  "name": "myObject"
}

Most Google API client libraries use at least one of these methods. To get more info on how to use each of the methods, click here

Example 2: Google Drive API share file

Each Google Drive file has associated Permissions resources. Each resource identifies the permission for a specific type and role, for example, “commenter” or “reader”. To share a file or folder, the user must have the writer role. 

Tip: the complete list of roles and the operations permitted by each can be found here.

The following fields are necessary when creating a permission:

  • Type. It identifies the scope of the permission – user, group, domain or anyone. 
  • Role. It identifies the operations that the type can perform.

Here’s an example of performing a permission with a client library.

String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
JsonBatchCallback<Permission> callback = new JsonBatchCallback<Permission>() {
  @Override
  public void onFailure(GoogleJsonError e,
                        HttpHeaders responseHeaders)
      throws IOException {
    // Handle error
    System.err.println(e.getMessage());
  }

  @Override
  public void onSuccess(Permission permission,
                        HttpHeaders responseHeaders)
      throws IOException {
    System.out.println("Permission ID: " + permission.getId());
  }
};
BatchRequest batch = driveService.batch();
Permission userPermission = new Permission()
    .setType("user")
    .setRole("writer")
    .setEmailAddress("[email protected]");
driveService.permissions().create(fileId, userPermission)
    .setFields("id")
    .queue(batch, callback);

Permission domainPermission = new Permission()
    .setType("domain")
    .setRole("reader")
    .setDomain("example.com");
driveService.permissions().create(fileId, domainPermission)
    .setFields("id")
    .queue(batch, callback);

batch.execute();

You can find more information on sharing files, folders and drives here

Example 3: Google Drive API search for files and list files in folder

To search for a specific set of files and folders, you should use the query string q with files.list to filter the files to return.

The following example demonstrates the format of a query string:

query_term operator values

Where:

  • query_term is the query term or field to search upon. To look through the query terms which can be used to filter shared drives, cite Search query terms
  • operator designates the condition for the query term. You can refer to Query operators to view which operators you can use with each query term.
  • values are the specific values you are using to filter your search results.

The following example demonstrates how to use a client library to filter search results to file names and IDs of JPEG images.

String pageToken = null;
do {
  FileList result = driveService.files().list()
      .setQ("mimeType='image/jpeg'")
      .setSpaces("drive")
      .setFields("nextPageToken, files(id, name)")
      .setPageToken(pageToken)
      .execute();
  for (File file : result.getFiles()) {
    System.out.printf("Found file: %s (%s)\n",
        file.getName(), file.getId());
  }
  pageToken = result.getNextPageToken();
} while (pageToken != null);

More examples are available here

Example 4: Google Drive spreadsheet API

To create a new spreadsheet, you should use create() method on the spreadsheet collection as it is shown in the example below. 

Spreadsheet spreadsheet = new Spreadsheet()
        .setProperties(new SpreadsheetProperties()
                .setTitle(title));
spreadsheet = service.spreadsheets().create(spreadsheet)
        .setFields("spreadsheetId")
        .execute();
System.out.println("Spreadsheet ID: " + spreadsheet.getSpreadsheetId());

Example 5: Google Drive API delete file

To skip the trash, you can permanently delete file by ID. The currently authenticated user must own the file or be an organizer on the parent for shared drive files. The code example for this method:

import com.google.api.services.drive.Drive;
 
import java.io.IOException;
// ...
 
public class MyClass {
 
  // ...
 
  /**
   * Permanently delete a file, skipping the trash.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to delete.
   */
  private static void deleteFile(Drive service, String fileId) {
    try {
      service.files().delete(fileId).execute();
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }
  }
 
  // ...
 
}

Google Drive API Documentation

You can find the necessary Google Drive API documentation here. It contains all the files on working with API for developers and also on integration of it into your website. 

Google Drive API limits and pricing

Google Drive API usage is totally free for users worldwide. Although it has some usage limits:

RequestsLimits
Requests per day 1,000,000
Requests per 100 seconds per user1,000

You can find a link to request more quota in the “Quotas” tab – if you need more than the default. Also, to find more information about pricing, check this page.  

FAQ

I’ve got insufficient permission for the Google Drive API. What should I do?

Choose the correct scope from the list here. This should solve the problem with insufficient Google Drive API permission.

How can I get help with the Drive API?

You can use Q&A website Stack Overflow to post your technical questions. Developers usually use tag [google-drive-api] to mark questions relevant to this service.

How much does Google Drive API cost?

The usage of Google Drive API is completely free. But there are some limits. You can see the table at the Pricing section above.

How can I start using the Drive API?

You can try a Quickstart option to configure and run your first Google Drive app.

Conclusion

As you can see, working with Google Drive API is not that hard. Getting the API key will take less than three minutes and this Drive API tutorial will come in handy.

Now tell us, do you use this tool? Have you ever faced any difficulties while working with it? Share your thoughts in the comments! And don’t forget to check our blog soon to get more useful guides. 

Black Friday Sale
50% OFF
The Biggest Sale of the Year. Don't Miss Out!
Grab The Deal