javascriptnode.jsgoogle-drive-apigoogle-docs-api

Reading a google doc without user login


I am trying to create a simple webpage that loads text from a google doc I have. The page will only ever read from the doc and will run client side, no server as the page is hosted on github. No need for users to login.

For example a section of text in the Google doc will hold descriptions for projects I have made. The web page will pull this text into a string and display it to the client.

I have set up a google cloud project, enabled the google doc api, and set up an api key. I have tried digging through Google's documentation but am getting lost in the swath of information geared towards bigger projects that are seemingly meant to access and modify different google account's docs. I've also tried finding similar solutions here but they all deal with google sheets and I cant even identify what might be calls to google or how to even start on the code side of this.

I am also extremely new to using Google api so this is all becoming overwhelming for what I thought would be a simple action. I Thought I could just pass the key and doc id into some api call and get the doc.

How do I use Javascript and or Node.js to let my page simply grab the data from a doc?

Update Here is the function I now have

async function printGoogleDoc(docID, apiKey){
await fetch(`https://www.googleapis.com/drive/v3/files/${docID}/export?mimeType=text/plain&key=${apiKey}`)
.then(function(res) {
    return res.text();
}).then(function(text) {
    console.log(text);
}).catch(function() {
    console.log("error");
});
}

This uses the Drive API rather than the Doc API, which is what I thought I needed to use, and prints the contents of the doc. Now with more experimenting I will be able to store the contents and use them how I wish.


Solution

  • This is just my guess. I believe your goal is as follows.

    In this case, how about the following method?

    Pattern 1

    In this pattern, "Method: files.export" of Drive API is used. Please replace {documentId} and {your API key} with the Google Document ID of your Google Document and your API key, respectively. In this case, Drive API is required to be enabled at the API console. And, please request the following URL with the GET method. By this, the Google Document is exported as text data.

    https://www.googleapis.com/drive/v3/files/{documentId}/export?mimeType=text%2Fplain&key={your API key}
    

    Pattern 2

    In this pattern, exportLinks of "Method: files.get" of Drive API is used. Please replace {documentId} with the Google Document ID of your Google Document. In this case, when the Document is publicly shared, the API key is not required to be used. And, please request the following URL with the GET method. By this, the Google Document is exported as text data.

    https://docs.google.com/feeds/download/documents/export/Export?exportFormat=txt&id={documentId}