Ok so after banging my head against this question for a while I have found something interesting..
When using Document ID 2PACX we get a 404. At first I thought it was a something related to service account not having proper permissions. Just for the record:
Still I got 404.
So, I tried a different method, I used the drive method to fetch all the documents and I found that the document that I wanted to fetch was associated to different ID.
Document ID from doc was "2PACX-1vTuwWllBnBa9StNEd1JzUI0sFi2jqOHG0sjL6WeN8j0Nv2nvP0UAETpEKx3zZDt2FqDKIdseJLOdKhT"
Document ID from drive fetch api was "1Hk-WnhWbE3yjfx0jKmrtbBN3CJsMtRIsCDauELOma2o"
I am not sure if there is some mismatch or that is how these IDs are intended to work. Anyways I modified your code with this knowledge and it seems to works. (FYI, just like google doc API u will need to enable drive API for this to work)
Please let me know if this helps to achieve what you want or do we need to strictly do it with using drive API
const { google } = require("googleapis")
const auth = new google.auth.GoogleAuth({
keyFile: "<path_to_service_account_key_json_file>",
scopes: [
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive.readonly"
]
})
async function getDocumentContents(documentId) {
try {
const authClient = await auth.getClient();
const response = await google.docs({ version: "v1", auth: authClient }).documents.get({ documentId: documentId })
return response.data;
} catch (error) {
console.error(error)
}
}
async function getDocumentID() {
try {
const authClient = await auth.getClient();
const drive = google.drive({ version: "v3", auth: authClient });
/*
In my case I know that i want to get file by name "Test" else u can use something like -
q: `name = ${fileName} and mimeType = 'application/vnd.google-apps.document'`
also u can fetch specific fileds only by passing fields parameter
fields: 'files(id, name)',
*/
const specificFileData = await drive.files.list({
q: `name = "Test" and mimeType = 'application/vnd.google-apps.document'`
});
return specificFileData.data.files[0].id;
} catch (error) {
console.error(error);
}
}
(async () => {
const documentId = await getDocumentID();
const documentContents = await getDocumentContents(documentId)
console.log('documentContents', documentContents.body.content)
})()