How to use "fields" of Drive APIs

There are a lot of APIs on Google. When we use Google Drive APIs, they usually have “fields” as a resource. The parameter “fields” gives various information which is selected to us. This is one of important parameters. And this can be used at Google Apps Script (GAS) although that version is v2. About how to use it, there are some documents. But it is difficult to find how to use it at GAS. So I would like to write down here as a memorandum. Most parameters for APIs have to be expressed as JSON. However, the expressions are different for each API. I would like to introduce this using some samples. This is for GAS.

1. Drive.Files.list

var params = {
    q:      "title='sample' and trashed=false",
    fields: "items(id, title, mimeType), kind"
};
var res = Drive.Files.list(params)
Logger.log(JSON.stringify(res))

{
  "kind": "drive#fileList",
  "items": [
    {
      "id": "FILE ID",
      "mimeType": "mimeType",
      "title": "FILE NAME"
    }
  ]
}

q is used at “Search for Files”. At this sample, it searches file name of “sample” outside trash box.

fields is expressed as above. title, id and ‘‘mimeType’’ are file name, file id and mime type of the file, respectively. kind is “This is always drive#fileList.” from document.

2. Drive.Files.get

var params = {
    fields: "id, title, mimeType"
};
var dat = Drive.Files.get("FILE ID", params);
Logger.log(JSON.stringify(dat))

{
  "id": "FILE ID",
  "mimeType": "mimeType",
  "title": "FILE NAME"
}

For example, title, id and mimeType are file name, file id and mime type of the file, respectively.

3. Drive.Files.insert

var data = {
    title:    "sample",
    mimeType: "application/vnd.google-apps.spreadsheet",
    parents:  [{"id": "FOLDER ID"}]
};
var res = Drive.Files.insert(data);
Logger.log("{id: %s, title: %s, mimeType: %s}", res.id, res.title, res.mimeType)

{
  "id": "FILE ID",
  "title": "sample",
  "mimeType": "application/vnd.google-apps.spreadsheet"
}

By this, a new spreadsheet is created under the FOLDER ID. In this case, “fields” is retrieved from the results of execution.

 Share!