Using Google Docs' API: Steps & Low-Code Examples (2023)

With millions of users worldwide, there is a high chance you use Google Docs at work to create, share, and collaborate on documents. But did you know Google Docs also has a convenient API you can use to automate Google Docs tasks? In this article, we'll explore how to use this API to read, parse, create and update Google documents.

Google Docs Limitations

While Google Docs is a powerful tool, it does have some limitations.

First, it has limited support for images. If you've ever tried to copy/paste images from Google Docs to a CMS like Notion, for example, you might notice images aren't imported correctly. You'll also need a plugin to download images stored in a Google Docs.

Google Docs also has poor Markdown support, which can be difficult to publish rich-text content in any headless CMS. More generally, Google Docs lacks features to create complex, data-driven documents.

All of these problems can be solved using Google Docs' API.

1. Google Docs API Setup

After creating a new Rowy project, enable the Google Docs API in your Google Cloud console.

Because Rowy is built on top of Google Cloud Functions, you don't need to worry about setting up OAuth2 via service accounts. Rowy directly integrates with Google Auth, so you can create an auth client for Google Docs' API in just 2 lines of code:

const gauth = new docs.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/documents']
  });
const authClient = await gauth.getClient();

2. Reading A Document From Google Docs

Importing a Google Doc just takes a minute. The only thing you'll need is the document ID, which you can find in the URL of the document.

For this example, we can create a new Rowy table containing a docId column and a read Action. Put the document ID in the docId column, and then run the read Action to import the document:

 - 0.webp

The read Action will return a JSON object containing the document's title, body, and other metadata. We store it in a doc column in the same row:

const action:Action = async ({ row, ref, auth, logging }) => {
  const docs = require('@googleapis/docs')

  const gauth = new docs.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/documents']
  });
  const authClient = await gauth.getClient();

  const client = await docs.docs({
      version: 'v1',
      auth: authClient
  });

  const res = await client.documents.get({
    documentId: row.docId
  })

  ref.update({
    doc: res.data
  })

  return {
    success: true
  }
}

3. Parsing A Google Doc

A Google Docs document is a JSON structure you need to parse to transform into another format like Markdown or HTML. For example, to convert a plain text document to Markdown, you can use the document's body previously obtained and convert paragraph fields to their Markdown equivalent:

const content = row.body.content
const size = content.length

let md = `#${row.title}\n\n`

for(let i = 0 ; i < size ; i++){
    const element = content[i]

    if(element.hasOwnProperty('paragraph')){
        const elements = element.paragraph.elements
        const size_elements = elements.length

        for(let j = 0 ; j < size_elements ; j++){
            const element = elements[j]

            if(element.hasOwnProperty('textRun')){
                const text = element.textRun.content
                md += `${text}\n`
            }
        }

        md += '\n'
    }
}

Depending on the document's complexity, you will need to parse other fields for your use case. Google documents are divided into structural elements (paragraph, section break, table, and table of contents). And then paragraphs encapsulate a variety of elements like text (textRun), images (inlineObjectElement), or list items (Bullet).

Check out the documentation for a full list of document elements.

4. Creating A New Google Doc

Creating a new Google Doc also takes a single line of code:

const res = await client.documents.create({
    requestBody: {
        title: 'Your new document!',
    },
})

Note that the create method returns a documentId you can use to add content to the document afterwards with the batchUpdate method. There is no parameter to directly add content.

5. Updating A Google Doc

Google documents follow an operational transform model, which means you can't directly update a document. Instead, you need to create a list of changes to apply to the document. This is what allows multiple users to edit the same document at the same time, as well as document versioning.

Because of this, updating a Google Doc is a bit complex to do programmatically. What it's useful for, however, is appending content to a new document―to publish a Markdown document to a Google Doc, for example. You could also do things like downloading all the images from a given document, optimizing them with the correct aspect ratio and file format, and then replace them in the original Google document.

To apply changes, you need to use the batchUpdate method. For example, to insert a new paragraph at the beginning of a newly created document:

await client.documents.batchUpdate({
    documentId: row.docId,
    requestBody: {
      requests: [
          {
              'insertText': {
                  location: {
                    index: 1
                  },
                  'text': 'some plain text'
              }
          }
      ]
    }
  })

The method takes an array of change requests as a parameter. You can find a full list of request types in the documentation like insertText to add text, replaceImage to switch an image with another, or createParagraphBullets to create a list.

Join Rowy's Community

That's a wrap! Hope this article helped you clear out how to create, read, and update documents using Google Docs' API.

If you have any questions, feel free to join our community on Discord. We're happy to provide assistance with Rowy.

Get started with Rowy in minutes

Continue reading

Browse all