Reputation: 65
Google Drive topic Is there a way to get the "folder name" with the file_id or the folder_id?
Upvotes: 1
Views: 10116
Reputation: 912
This can not be done in a single call its needs to be two. First you find the parent id of the file id you have then you need to request the name of the folder using the parent id that was returned to you from the first call.
GET https://www.googleapis.com/drive/v3/files/[FileId]?fields=parents
Will give you the parent id of the folder that the file is currently in
GET https://www.googleapis.com/drive/v3/files/[ParentId]?fields=name
Will give you the name of the parent folder
Here is an easy example made with "node.js"
We are searching for a filename "123", once found search for a parent id
Callbacks way:
function getParentID(auth) {
const drive = google.drive({
version: 'v3',
auth
});
drive.files.list({
q: "name = '123'"
}, (err, res) => {
if (err) return console.log('#1001 - The API returned an error: ' + err);
const fileId = res.data.files[0].id;
console.log("File ID : ", fileId);
drive.files.get({
fileId: fileId,
fields: "parents"
}, (err, res) => {
if (err) return console.log('#1002 - The API returned an error:' + err);
console.log("Parent folder ID :", res.data.parents[0])
})
});
}
Promises way:
function getParentID2(auth) {
const drive = google.drive({
version: 'v3',
auth
});
drive.files.list({
q: "name = '123'"
}).then((res) => {
const fileId = res.data.files[0].id;
console.log("File ID : ", fileId);
drive.files.get({
fileId: fileId,
fields: "parents"
}).then((res) => {
console.log("Parent folder ID :", res.data.parents[0])
})
}).catch((err) => {
console.log(err.response.data)
})
}
Output:
File ID : 2xU_zgmOcjOIterprt91wibEEKU8fuNI-yZuBcgvEFjY
Parent folder ID : 2KQve4H24jlgJKcywGRBJaOnTK2tDLZgR
Upvotes: 6
Reputation: 116868
This can not be done in a single call its needs to be two. First you find the parent id of the file id you have then you need to request the name of the folder using the parent id that was returned to you from the first call.
GET https://www.googleapis.com/drive/v3/files/[FileId]?fields=parents
Will give you the parent id of the folder that the file is currently in
GET https://www.googleapis.com/drive/v3/files/[ParentId]?fields=name
Will give you the name of the parent folder
Upvotes: 2