このガイドでは、Google Drive API でファイルやフォルダを検索する方法について説明します。
list メソッドを
files リソースで使用すると、
ドライブ ユーザーのファイルとフォルダのすべてまたは一部を返すことができます。list
メソッドを使用して、一部のリソース メソッド(
get メソッドや update メソッドなど)に必要な fileId を取得することもできます。
fields パラメータを使用する
レスポンスで返すフィールドを指定する場合は、
fields システム
パラメータ
を files リソースの任意のメソッドで設定します。fields パラメータを省略すると、サーバーはメソッド固有のデフォルトのフィールド セットを返します。たとえば、
list メソッドは、各ファイルの kind、id、
name、mimeType、および resourceKey フィールドのみを返します。別の
フィールドを返す方法については、特定のフィールドを返すをご覧ください。
ID でファイルを取得する
ファイルを取得するには、get メソッドを
files リソースに fileId パスパラメータとともに使用します。
ファイル ID がわからない場合は、すべてのファイルを一覧表示するには、list
メソッドを使用します。
このメソッドは、ファイルを files リソースのインスタンスとして返します。alt=media パラメータを指定すると、レスポンスの本文にファイルの内容が含まれます。Blob ファイルをダウンロードするには、Blob ファイルの内容をダウンロードするをご覧ください。
既知のマルウェアやその他の
不正なファイルをダウンロードするリスクを認識するには、
acknowledgeAbuse クエリ パラメータを true に設定します。このフィールドは、alt=media パラメータが設定されていて、ユーザーがファイルのオーナーであるか、ファイルが存在する共有ドライブの管理者のいずれかである場合にのみ適用されます。
マイドライブ内のすべてのファイルとフォルダを一覧表示する
パラメータを指定せずに list メソッドを使用すると、現在のユーザーのマイドライブ内のすべてのファイルとフォルダが返されます。
次の curl コマンドは、すべてのファイルを一覧表示する方法を示しています。
curl -X GET \
'https://www.googleapis.com/drive/v3/files' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-H 'Accept: application/json'
ACCESS_TOKEN は、承認済みの OAuth 2.0 アクセス トークンに置き換えます。
マイドライブ内の特定のファイルとフォルダを検索する
現在のユーザーのマイドライブ内の特定のファイルまたはフォルダのセットを検索するには、クエリ文字列 q フィールドを list メソッドで使用して、1 つ以上の検索キーワードを組み合わせて返すファイルをフィルタします。
クエリ文字列の構文には、次の 3 つの部分が含まれます。
query_term operator values
ここで
query_termは、検索するクエリキーワードまたはフィールドです。operatorは、クエリキーワードの条件を指定します。valuesは、検索結果をフィルタするために使用する特定の値です。
たとえば、次のクエリ文字列は、MIME タイプを設定して フォルダのみを返すように検索をフィルタします。
mimeType = 'application/vnd.google-apps.folder'
すべてのファイル クエリキーワードを表示するには、ファイル固有のクエリキーワードをご覧ください。
クエリの作成に使用できるすべてのクエリ演算子を表示するには、クエリ 演算子をご覧ください。
クエリ文字列の例
次の表に、基本的なクエリ文字列の例を示します。実際のコードは、検索に使用するクライアント ライブラリによって異なります。
クエリが正しく機能するように、ファイル名内の特殊文字もエスケープする必要があります。たとえば、ファイル名にアポストロフィ
(')とバックスラッシュ("\")の両方の文字が含まれている場合は、バックスラッシュを使用してエスケープします(name
contains 'quinn\'s paper\\essay')。
| クエリ対象 | 例 |
|---|---|
文字列一致演算子(contains) |
|
| 「hello」という単語を含むファイル | fullText contains 'hello' |
| 「hello world」というフレーズを含むファイル | fullText contains '"hello world"' |
| 「\」文字を含むクエリを含むファイル(例: 「\authors」) | fullText contains '\\authors' |
| 「budget」を含む名前のファイル | name contains 'budget' |
等価演算子と不等価演算子(=、!=) |
|
| 「hello」という名前のファイル | name = 'hello' |
| フォルダであるファイル | mimeType = 'application/vnd.google-apps.folder' |
| フォルダではないファイル | mimeType != 'application/vnd.google-apps.folder' |
| スター付きのファイル | starred = true |
| ゴミ箱内のファイル | trashed = true |
| ゴミ箱にないファイル | trashed = false |
| 特定のファイル ID を指すショートカット | shortcutDetails.targetId = '1987654321' |
| 誰ともドメインとも共有されていないファイル(非公開、または特定のユーザーやグループと共有されている) | visibility = 'limited' |
| リンクを知っているすべてのユーザーがアクセスできるファイル | visibility = 'anyoneWithLink' |
| ウェブ上で一般公開されているファイル | visibility = 'anyoneCanFind' |
比較演算子(>、>=、<、<=) |
|
| 指定した日付以降に変更されたファイル(デフォルトのタイムゾーンは UTC) | modifiedTime > '2012-06-04T12:00:00' |
| 2023 年 1 月 1 日以降に作成されたファイル | createdTime > '2023-01-01T00:00:00' |
| 2023 年 1 月 1 日より前に変更されたファイル | modifiedTime < '2023-01-01T00:00:00' |
コレクション メンバーシップ演算子(in) |
|
コレクション内の直接の子ファイル(例: parents コレクション内のフォルダ ID) |
'1234567' in parents |
| アプリケーション データ フォルダ内のファイル | 'appDataFolder' in parents |
| ユーザー「test@example.org」がオーナーであるファイル | 'test@example.org' in owners |
| ユーザー「test@example.org」に書き込み権限があるファイル | 'test@example.org' in writers |
| グループ「group@example.org」のメンバーに書き込み権限があるファイル | 'group@example.org' in writers |
| ユーザー「test@example.org」に読み取り権限があるファイル | 'test@example.org' in readers |
コレクション一致演算子(has) |
|
| すべてのアプリに表示されるカスタム ファイル プロパティを持つファイル | properties has { key='mass' and value='1.3kg' } |
| リクエスト元のアプリに非公開のカスタム ファイル プロパティを持つファイル | appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' } |
| キーが「department」のカスタム ファイル プロパティを持つファイル(値に関係なく) | properties has { key='department' } |
論理演算子(and、or、not) |
|
| 「hello」と「goodbye」という単語を含む名前のファイル | name contains 'hello' and name contains 'goodbye' |
| 「hello」という単語を含まない名前のファイル | not name contains 'hello' |
| 「important」というテキストを含み、ゴミ箱にあるファイル | fullText contains 'important' and trashed = true |
| 「hello」という単語を含まないファイル | not fullText contains 'hello' |
| 特定の日付以降に変更された画像ファイルまたは動画ファイル | modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/') |
| 承認されたユーザーと共有され、名前に「hello」が含まれるファイル | sharedWithMe and name contains 'hello' |
| フォルダまたはショートカットであるファイル | mimeType = 'application/vnd.google-apps.folder' or mimeType = 'application/vnd.google-apps.shortcut' |
| 「Project Plan」という名前で、ゴミ箱にないファイル | name = 'Project Plan' and trashed = false |
| ゴミ箱にない特定のフォルダ内の直接の子ファイル | '1234567' in parents and trashed = false |
クライアント ライブラリで検索結果をフィルタする
次のコードサンプルは、クライアント ライブラリを使用して、検索結果を JPEG ファイルのファイル名と ID にフィルタする方法を示しています。このサンプルでは、mimeType クエリキーワードを使用して、結果を image/jpeg タイプのファイルに絞り込みます。また、
spaces を drive に設定して、検索範囲を ドライブ
スペースに絞り込みます。nextPageToken が null を返すと、結果はなくなります。
Java
Python
Node.js
PHP
一般公開フォルダ内のファイルを一覧表示する
一般公開されているフォルダ(アクセス権が
[リンクを知っている全員] または [ウェブ上で一般公開] に設定されている)内のファイルを検索または一覧表示するには、list メソッドを files リソースで使用し、q クエリ
パラメータを設定して parents コレクション内のフォルダ ID でフィルタします。
'FOLDER_ID' in parents and trashed = false
一般公開フォルダ内のファイルを一覧表示する場合は、OAuth 2.0
ユーザー認証情報の代わりに
API キーを使用してリクエストを認証できます。フォルダが共有ドライブ内にある場合は、リクエストで supportsAllDrives=true と includeItemsFromAllDrives=true も設定する必要があります。
次のコードサンプルは、一般公開フォルダ内のファイルを一覧表示する方法を示しています。
Node.js
/**
* List files in a public folder using an API key.
* @param {string} folderId The ID of the public folder.
* @param {string} apiKey Your Google Cloud API key.
* @return {Promise<Array>} The list of files.
*/
async function listPublicFolder(folderId, apiKey) {
const {google} = require('googleapis');
const service = google.drive({version: 'v3', auth: apiKey});
try {
const response = await service.files.list({
q: `'${folderId}' in parents and trashed = false`,
fields: 'nextPageToken, files(id, name, mimeType)',
supportsAllDrives: true,
includeItemsFromAllDrives: true,
});
const files = response.data.files;
console.log('Files:');
for (const file of files) {
console.log(`${file.name} (${file.id})`);
}
return files;
} catch (err) {
// TODO(developer): Handle error
console.error(err);
}
}
curl
curl -G \
'https://www.googleapis.com/drive/v3/files' \
--data-urlencode "q='FOLDER_ID' in parents and trashed = false" \
--data-urlencode 'supportsAllDrives=true' \
--data-urlencode 'includeItemsFromAllDrives=true' \
--data-urlencode 'fields=nextPageToken,files(id,name,mimeType)' \
--data-urlencode 'key=API_KEY' \
-H 'Accept: application/json'
次のように置き換えます。
- FOLDER_ID: 一般公開フォルダの ID。
- API_KEY: プロジェクトの API キー。
下位のフォルダとファイルを再帰的に検索する
parents クエリキーワードは、指定したフォルダ内にある直接の子ファイルとフォルダのみを返します。Drive API には、1 回の API 呼び出しで下位のサブフォルダ ツリーを再帰的に検索するクエリ演算子またはパラメータはありません。
フォルダとその下位のすべてのサブフォルダとファイルを検索するには、アプリケーションでクライアントサイドのツリー走査を行う必要があります。
-
'FOLDER_ID' in parents and trashed = falseを使用して、ターゲット フォルダの直接の子をクエリします。 mimeType = 'application/vnd.google-apps.folder'の結果をフィルタして、サブフォルダを特定します。- 各子フォルダの ID を再帰的または反復的にクエリして、その内容を取得します。
次のコードサンプルは、フォルダとその下位を再帰的に検索する方法を示しています。
Node.js
/**
* Recursively searches a folder and all descendant subfolders for files.
* @param {string} folderId The ID of the starting folder.
* @param {Object} authClient An authorized OAuth 2.0 client.
* @return {Promise<Array>} The list of all descendant files.
*/
async function searchFolderRecursively(folderId, authClient) {
const {google} = require('googleapis');
const service = google.drive({version: 'v3', auth: authClient});
const allFiles = [];
const foldersToSearch = [folderId];
try {
while (foldersToSearch.length > 0) {
const currentFolderId = foldersToSearch.pop();
let pageToken = null;
do {
const response = await service.files.list({
q: `'${currentFolderId}' in parents and trashed = false`,
fields: 'nextPageToken, files(id, name, mimeType)',
pageSize: 1000,
supportsAllDrives: true,
includeItemsFromAllDrives: true,
pageToken: pageToken,
});
const files = response.data.files || [];
for (const file of files) {
if (file.mimeType === 'application/vnd.google-apps.folder') {
foldersToSearch.push(file.id);
} else {
allFiles.push(file);
}
}
pageToken = response.data.nextPageToken;
} while (pageToken);
}
return allFiles;
} catch (err) {
// TODO(developer): Handle error
console.error(err);
throw err;
}
}
Python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
def search_folder_recursively(folder_id, creds):
"""Recursively searches a folder and all descendant subfolders for
files.
Args:
folder_id: The ID of the starting folder.
creds: An authorized OAuth 2.0 credentials object.
Returns:
A list of all descendant file resources.
"""
service = build("drive", "v3", credentials=creds)
all_files = []
folders_to_search = [folder_id]
try:
while folders_to_search:
current_folder_id = folders_to_search.pop()
page_token = None
while True:
response = (
service.files()
.list(
q=f"'{current_folder_id}' in parents and trashed = false",
fields="nextPageToken, files(id, name, mimeType)",
pageSize=1000,
supportsAllDrives=True,
includeItemsFromAllDrives=True,
pageToken=page_token,
)
.execute()
)
for item in response.get("files", []):
if (
item.get("mimeType")
== "application/vnd.google-apps.folder"
):
folders_to_search.append(item.get("id"))
else:
all_files.append(item)
page_token = response.get("nextPageToken")
if not page_token:
break
return all_files
except HttpError as error:
# TODO(developer): Handle error
print(f"An error occurred: {error}")
return None
カスタム プロパティを持つファイルを検索する
カスタム ファイル プロパティを持つファイルを検索するには、キーと値を使用して properties または appProperties 検索クエリキーワードを使用します。たとえば、リクエスト元のアプリに非公開のカスタム ファイル プロパティ additionalID を値 8e8aceg2af2ge72e78 で検索するには、次のようにします。
appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
詳細については、カスタム ファイル プロパティを追加するをご覧ください。
ラベルまたはフィールド値でファイルを検索する
特定のラベルが付いたファイルを検索するには、labels 検索クエリキーワードを特定のラベル ID とともに使用します。
特定のラベルが適用されているファイルを検索するには:
'labels/LABEL_ID' in labels
特定のラベルが適用されていないファイルを検索するには:
not 'labels/LABEL_ID' in labels
特定のラベル フィールドの値に基づいてファイルを検索するには:
labels/LABEL_ID.FIELD_ID = 'VALUE'
成功した場合、レスポンスの本文にはクエリに一致するすべてのファイル インスタンスが含まれます。詳細については、特定のラベルまたは フィールド値を持つファイルを検索するをご覧ください。
コーパス全体を検索する
`list` メソッドを使用すると、デフォルトで `user` アイテム コレクションが `corpora` クエリ パラメータ`
`に設定されます。domain と共有されているアイテム コレクションなど、他のアイテム コレクションを検索するには、corpora パラメータを明示的に設定する必要があります。
1 つのクエリで複数のコーパスを検索できますが、結合されたコーパスが大きすぎると、API から不完全な結果が返される可能性があります。レスポンスの本文で
incompleteSearch
フィールドを確認します。true の場合、一部のドキュメントが省略されています。この問題を解決するには、corpora を絞り込んで user または drive を使用します。
orderBy クエリ
パラメータを list メソッドで使用する場合は、createdTime キーを
大きなアイテム コレクションのクエリに使用しないでください。追加の処理が必要になり、
タイムアウトやその他の問題が発生する可能性があります。大きなアイテム コレクションで時間に関連する並べ替えを行う場合は、modifiedTime を使用できます。これは、これらのクエリを処理するように最適化されています。
たとえば、orderBy を modifiedTime(または modifiedTime desc)に設定します。
orderBy クエリ パラメータを省略すると、デフォルトの並べ替え順序はなく、アイテムは任意に返されます。