Google Docs API Examples

Real world examples using the Google Doc's API. Screenshots of generated docs, code snippets, and explanation of quirks!

Google Docs API Examples (REST API v1)

Google’s API documentation can be dense. I’ve wrestled with their documentation many times to try and understand how to use their API’s. For this reason, I thought I’d create a resource to share with others with examples of Google’s Docs API in use. These examples are in Javascript using Google’s REST API. For reference, here’s the link to Google Docs official documentation . I intend for this to be a living resource. I plan to add to it as I come up across more examples.

Table of Contents

Authorizing Requests

Create a Document

Insert Text into a Document

Formatting text

Authorizing Requests

Authorizing requests to the Google Doc’s API requires either an API key or an OAuth 2.0 token .

Create a Document

let fetch_url = `https://docs.googleapis.com/v1/documents?key=${API_KEY}`;

let fetch_options = {
  method: "POST",
  headers: {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Example of a Doc created programmatically",
  }),
};

fetch(fetch_url, fetch_options)
  .then((res) => res.json())
  .then((res) => {
    console.log(res);
  });

Insert Text into a Document

const documentID = "ID_OF_DOCUMENT_YOU_ARE_ADDING_TO";

let fetch_url = `https://docs.googleapis.com/v1/documents/${documentID}:batchUpdate?key=${API_KEY}`;

let fetch_options = {
  method: "POST",
  headers: {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    requests: [
      {
        insertText: {
          text: "test this out",
          location: {
            index: 1,
          },
        },
      },
    ],
  }),
};

fetch(fetch_url, fetch_options)
  .then((res) => res.json())
  .then((res) => {
    console.log(res);
  });

If you don’t know where to find the documentID, you can get it from taking res.documentId from the Create a Document example

Formatting text

This section covers various different examples of formatting text

Inserting bolded text

This example will create a document, add text, and bold the text.

Bolded Text Document

Here’s the code:

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

const dateForTitle = month + "/" + day + "/" + year;
let fetch_options = {
  method: "POST",
  headers: {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: `Google Doc's Demo ${dateForTitle}`,
  }),
};

fetch(fetch_url, fetch_options)
  .then((res) => res.json())
  .then((res) => {
    const documentID = res.documentId;

    let textForDoc = "Let's bold this text";

    requests = [
      {
        insertText: {
          text: textForDoc,
          location: {
            index: 1,
          },
        },
      },
      {
        updateTextStyle: {
          textStyle: {
            bold: true,
          },
          fields: "bold",
          range: {
            startIndex: 1,
            endIndex: textForDoc.length + 1,
          },
        },
      },
    ];

    let fetch_url = `https://docs.googleapis.com/v1/documents/${documentID}:batchUpdate?key=${API_KEY}`;

    let fetch_options = {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        requests: requests,
      }),
    };

    fetch(fetch_url, fetch_options)
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
      });
  });

Multiple lines with bold, italic, background color

Let’s tackle a more complicated example:

Document with multiple lines, bold, background color

A note about adding content in reverse:

Google recommends building your document backwards. This way you don’t have to keep track of where in the document you are editing, you can just a location with index 1, which represents the top of the document.

From Google’s documentation:

Simplify matters by writing backwards. To avoid having to precalculate these offset changes, order your insertions to “write backwards”: do the insertion at the highest-numbered index first, working your way towards the beginning with each insertion. This ordering ensures that each write’s offsets are unaffected by the preceding ones.

The code:

let fetch_url = `https://docs.googleapis.com/v1/documents?key=${API_KEY}`;

let fetch_options = {
  method: "POST",
  headers: {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: `Google Doc's multiple lines with bold, italic, background color`,
  }),
};

fetch(fetch_url, fetch_options)
  .then((res) => res.json())
  .then((res) => {
    const documentID = res.documentId;

    const linesOfTextToEnter = [
      "This is line one",
      "This is line two.  We'll highlight this line!",
      "This is line three",
    ];

    // We'll put all our requests in here
    let requests = [];

    // This reverses the array so we can build the document backwards.
    // See the note about adding content in reverse.
    linesOfTextToEnter
      .slice()
      .reverse()
      .forEach((lineOfText, index) => {
        boldedText = `${lineOfText}:\n`;

        italicText = "Example text!\n";
        let italicTextStyle = {
          bold: false,
          italic: true,
        };

        // Let's put a background color on the second element in the linesOfTextToEnter array
        if (index == 1) {
          italicTextStyle.backgroundColor = {
            color: {
              rgbColor: {
                red: 1.0,
                green: 1.0,
                blue: 0.8,
              },
            },
          };
        }

        requests = requests.concat([
          {
            insertText: {
              text: boldedText,
              location: {
                index: 1,
              },
            },
          },
          {
            updateTextStyle: {
              textStyle: {
                bold: true,
              },
              fields: "bold",
              range: {
                startIndex: 1,
                endIndex: boldedText.length,
              },
            },
          },
          {
            insertText: {
              text: italicText,
              location: {
                index: boldedText.length + 1,
              },
            },
          },
          {
            updateTextStyle: {
              textStyle: italicTextStyle,
              fields: "bold,italic,backgroundColor",
              range: {
                startIndex: boldedText.length + 1,
                endIndex: boldedText.length + italicText.length,
              },
            },
          },
        ]);
      });
    const docHeaderText = "Google Doc's Examples!\n\n";
    requests = requests.concat([
      {
        insertText: {
          text: docHeaderText,
          location: {
            index: 1,
          },
        },
      },
      {
        updateTextStyle: {
          textStyle: {
            bold: false,
            italic: false,
            fontSize: {
              magnitude: 17,
              unit: "PT",
            },
          },
          fields: "bold,italic,fontSize",
          range: {
            startIndex: 1,
            endIndex: docHeaderText.length,
          },
        },
      },
      {
        updateParagraphStyle: {
          range: {
            startIndex: 1,
            endIndex: docHeaderText.length,
          },
          paragraphStyle: {
            alignment: "CENTER",
          },
          fields: "alignment",
        },
      },
    ]);

    let fetch_url = `https://docs.googleapis.com/v1/documents/${documentID}:batchUpdate?key=${API_KEY}`;

    let fetch_options = {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        requests: requests,
      }),
    };

    fetch(fetch_url, fetch_options)
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
      });
  });