How to add/create/insert files to Google Drive through the API

google apigoogle-api-clientgoogle-drive-api

Need help regarding inserting a file to google drive through api. The api documentation for this purpose does not clearly explains how to send the actual body of the file through http post request.

Best Answer

The documentation on insert operations already contains examples in a bunch of programming languages, here is how to do it using the HTTP based protocol of the Google Drive API.

First, POST the new file metadata to the Drive endpoint. It has to be in the form of a File resource JSON object:

POST /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
...

{
  "title": "file_name.extension",
  "mimeType": "mime/type",
  "description": "Stuff about the file"
}

The response body will be a JSON representation of the newly created File resource. It will look like:

{
  "kind": "drive#file",
  "id": string,
  "etag": etag,
  "selfLink": string,
  "title": "file_name",
  "mimeType": "mime/type",
  "description": "Stuff about the file"
  ...
  "downloadUrl": string,
  ...
}

This is a confirmation that the file entry has been created. Now you need to upload the content. To do that you need to take the ID of the file given by the id JSON attribute in the response above and PUT the content of the actual file to the upload endpoint with an OAuth 2.0 authorized request. It should look like:

PUT /upload/drive/v2/files/{id}?uploadType=media HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
Content-Type: mime/type

<file content here>

You are done :)

There is also a way to do this in 1 single POST request using a multipart request where you post the metadata of the file at the same time as the content. Here is an example:

POST /upload/drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
Content-Type: multipart/form-data; boundary=287032381131322
...

--287032381131322
Content-Type: application/json

{
  "title": "file_name.extension",
  "mimeType": "mime/type",
  "description": "Stuff about the file"
}
--287032381131322
Content-Type: mime/type

<file content here>
--287032381131322--

The response will contain the metadata of the newly created file. You may also use the Content-Transfer-Encoding: base64 header in the sub-part of the request to be able to pass the data of the file as Base 64 encoded.

Lastly there is also a resumable upload protocol which is convenient to upload large files, offer a pause/resume feature and/or upload files with flaky internet connection.

PS: most of this is now described in Drive's file upload documentation.