Javascript required
Skip to content Skip to sidebar Skip to footer

Google Drive Api Upload File Example Java

If you were planning to start working with Drive API by Google any fourth dimension shortly, we've prepared a complete guide for you. Today you'll learn what exactly it tin can be used for and likewise how to go an API central in a few steps.

Contents

  1. 1. What is Google Drive API
    • What tin can you practise using this tool
  2. ii. How to go Google Drive API key
  3. 3. Using Google Drive API: examples
    • Example 1: Drive API upload file
    • Example ii: Drive API share file
    • Case 3: Bulldoze API search for files and listing files in folder
    • Example iv: Drive spreadsheet API
    • Example 5: Drive API delete file
  4. iv. Google Bulldoze API documentation
  5. 5. Google Derive API limits and pricing
  6. 6. FAQ
  7. vii. Decision

What is Google Drive API

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

What can you practise using this tool

This choice can be used to:

  • Download and upload files to Drive.
  • Search for files and folders .
  • Create circuitous search queries that return whatever 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 proper noun, URL, concluding modified engagement, and user.
  • Create shortcuts which are external links to data kept outside of Drive, in a dissimilar information store or cloud storage organisation.
  • Class a defended folder to store your application's data to prevent the app from accessing all the user's content.
  • Integrate with the Drive UI which tin exist used to interact with Drive files.

To successfully work with API you've got to become an API Central. Permit'due south see how you lot can do information technology.

How to get Google Drive API central

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 utilize the resource. Y'all can get more data on roles here.

To set up an API primal, follow these steps:

  • Open the APIs & Services → Credentials board in the Cloud Google Drive API console.
Google Cloud Platform console
  • Pick Create credentials selection 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 tin apply your API key, you are gratis to add app restrictions based on your application blazon. Mind that you can only set up i restriction blazon per API primal.

Using Google Drive API: examples

At that place are several ways you may apply Google Bulldoze API. Let's discuss some of them.

Case ane: Google Drive API upload file

You lot can upload file data when you lot 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 asking.
  • Resumable upload. It can be performed for more reliable transfer, especially of import with large files.

This instance demonstrates a unproblematic upload request:

POST googleapis/upload/drive/v3/files?uploadType=media HTTP/i.1 Content-Type: image/jpeg Content-Length: [NUMBER_OF_BYTES_IN_FILE] Potency: Bearer [YOUR_AUTH_TOKEN]  [JPEG_DATA]        

A multipart upload asking can wait like this:

POST googleapis/upload/bulldoze/v3/files?uploadType=multipart HTTP/ane.1 Dominance: Bearer [YOUR_AUTH_TOKEN] Content-Blazon: multipart/related; purlieus=foo_bar_baz Content-Length: [NUMBER_OF_BYTES_IN_ENTIRE_REQUEST_BODY]  --foo_bar_baz Content-Blazon: awarding/json; charset=UTF-eight  {   "proper noun": "myObject" }  --foo_bar_baz Content-Blazon: prototype/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/ane.1 Authorization: Bearer [YOUR_AUTH_TOKEN] Content-Length: 38 Content-Blazon: application/json; charset=UTF-8 X-Upload-Content-Type: prototype/jpeg X-Upload-Content-Length: 2000000  {   "name": "myObject" }        

Nearly Google API client libraries use at to the lowest degree 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 resource. Each resources 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 author office.

Tip: the consummate listing of roles and the operations permitted by each can be found hither.

The following fields are necessary when creating a permission:

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

Here'south an instance 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 fault     Arrangement.err.println(east.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();        

Yous can find more than data on sharing files, folders and drives here.

Case three: Google Bulldoze API search for files and listing files in folder

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

The post-obit 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 tin can be used to filter shared drives, cite Search query terms.
  • operator designates the status for the query term. You can refer to Query operators to view which operators yous can utilise with each query term.
  • values are the specific values yous are using to filter your search results.

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

String pageToken = nothing; do {   FileList outcome = driveService.files().list()       .setQ("mimeType='paradigm/jpeg'")       .setSpaces("drive")       .setFields("nextPageToken, files(id, name)")       .setPageToken(pageToken)       .execute();   for (File file : result.getFiles()) {     System.out.printf("Found file: %s (%southward)\due north",         file.getName(), file.getId());   }   pageToken = effect.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 drove as it is shown in the example below.

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

Case v: Google Drive API delete file

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

import com.google.api.services.drive.Drive;   import java.io.IOException; // ...   public form MyClass {     // ...     /**    * Permanently delete a file, skipping the trash.    *    * @param service Drive API service instance.    * @param fileId ID of the file to delete.    */   individual static void deleteFile(Bulldoze service, String fileId) {     attempt {       service.files().delete(fileId).execute();     } catch (IOException east) {       Organisation.out.println("An mistake occurred: " + eastward);     }   }     // ...   }        

Google Bulldoze API Documentation

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

Google Drive API limits and pricing

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

Requests Limits
Requests per day 1,000,000
Requests per 100 seconds per user ane,000

You tin find a link to request more quota in the "Quotas" tab – if yous demand more than the default. Also, to find more information virtually pricing, check this page.

FAQ

I've got insufficient permission for the Google Drive API. What should I practice?

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 Bulldoze API?

Yous 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 toll?

The usage of Google Bulldoze API is completely gratis. But there are some limits. You lot tin come across the table at the Pricing section higher up.

How can I start using the Bulldoze API?

Decision

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

Now tell us, exercise you use this tool? Have y'all ever faced any difficulties while working with information technology? Share your thoughts in the comments! And don't forget to check our web log before long to get more useful guides.

hordernhationes.blogspot.com

Source: https://elfsight.com/blog/2020/03/how-to-use-google-drive-api-and-get-an-api-key/