Google drive API publish document and get published link

If I make a document in Google drive and type some text, I can later go to file => Publish to the Web and get a link to a public webpage-style of the google doc, along with an embed link.

This is how its done manually. How can I do this automatically with a Node.JS server script (for example, using a Service Account) using the Goolgle Drive API? I couldn't find anything about this particular thing in their docs, is this possible? DO I need to make a google script instead? Is it even possible with that?

Upvotes: 6

Views: 2828

Answers (1)

Tanaike
Tanaike

Reputation: 201553

  • You want to publish the Google Document to web using googleapis with Node.js.
  • You want to retrieve the published URL.
  • You want to achieve this using the service account.
  • You have already had the service account and been able to use Drive API.

From your question and replying comments, I could understand like this. If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Usage:

In order to use the following sample script, please do the following flow.

  1. Prepare a Google Document.
    • In this case, as a test case, please create new Google Document to your Google Drive.
  2. Share the created Google Document with the email of the service account as the writer.
  3. Retrieve the file ID of the Google Document.
  4. Set the variables to the following sample script.
  5. Run the script.
    • In this case, "Revisions: update" of Drive API is used.

By this, the Google Document is published to the web and you can see the published URL at the console.

Sample script:

const { google } = require("googleapis");

// Please set the email and private key of service account.
const auth = new google.auth.JWT(
  "### email of service account ###",
  null,
  "### private key of service account ###" ,
  ["https://www.googleapis.com/auth/drive"]
);
const fileId = "###"; // Please set the file ID.

const drive = google.drive({ version: "v3", auth });
const body = {
  resource: {
    published: true,
    publishedOutsideDomain: true,
    publishAuto: true
  },
  fileId: fileId,
  revisionId: 1
};
drive.revisions.update(body, err => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(`https://docs.google.com/document/d/${fileId}/pub`);
});
  • Please set the private key like "-----BEGIN PRIVATE KEY-----\n###\n-----END PRIVATE KEY-----\n".

Note:

  • The published URL is https://docs.google.com/document/d/${fileId}/pub. In this case, the file ID is used. Because unfortunately, in the current stage, the URL like https://docs.google.com/document/d/e/2PACX-###/pubhtml cannot be retrieved by Google API.

Reference:

Upvotes: 5

Related Questions