Skip to main content
RapidDev - Software Development Agency
retool-integrationsREST API Resource

How to Integrate Retool with Google Docs

Connect Retool to Google Docs using the Google Docs REST API Resource authenticated via a Google service account or OAuth 2.0. Once connected, your Retool app can read document content, create new documents from templates, and perform batch updates to insert or replace text — enabling document generation workflows where Retool form data populates Google Docs reports, contracts, or briefs automatically.

What you'll learn

  • How to configure a Google OAuth REST API Resource in Retool for Google Docs API access
  • How to read document content and structure from the Google Docs API
  • How to create new Google Docs documents from Retool forms and populate them with data
  • How to use batchUpdate to perform template-based text replacement in existing documents
  • How to build a document generation workflow that creates Docs from Retool database records
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate15 min read25 minutesOtherLast updated April 2026RapidDev Engineering Team
TL;DR

Connect Retool to Google Docs using the Google Docs REST API Resource authenticated via a Google service account or OAuth 2.0. Once connected, your Retool app can read document content, create new documents from templates, and perform batch updates to insert or replace text — enabling document generation workflows where Retool form data populates Google Docs reports, contracts, or briefs automatically.

Quick facts about this guide
FactValue
ToolGoogle Docs
CategoryOther
MethodREST API Resource
DifficultyIntermediate
Time required25 minutes
Last updatedApril 2026

Why connect Retool to Google Docs?

Teams that generate repetitive documents — sales proposals, customer reports, compliance summaries, onboarding checklists — often do this manually by copying templates and filling in values. Connecting Retool to Google Docs automates this workflow: a Retool form collects the inputs, queries pull related data from your database, and the Google Docs API creates a fully populated document in seconds. The result is saved to Google Drive and can be shared immediately, with no copy-paste required.

The Google Docs API's most powerful feature for Retool integrations is batchUpdate — a single API call that can perform multiple document operations atomically. For template-based generation, the pattern is: duplicate a template document (via Google Drive API), then use batchUpdate with replaceAllText operations to swap placeholder strings like {{CLIENT_NAME}} with actual values from your Retool form. This keeps the document formatting, styling, and structure intact while injecting fresh data.

Beyond document creation, Retool can read existing Google Docs to extract content for analysis, pull document metadata (title, last modified, owner) for a document management dashboard, or monitor specific documents for changes by comparing content snapshots. These read operations are simpler than writes and require fewer OAuth scopes. The integration is particularly valuable for teams already using Google Workspace who want to add automation without leaving the Google ecosystem.

Integration method

REST API Resource

Retool connects to Google Docs via the Google Docs REST API (v1) using a REST API Resource authenticated with Google OAuth 2.0 or a service account Bearer token. The API base URL is https://docs.googleapis.com/v1/. Retool proxies all requests server-side, keeping OAuth credentials off the browser. Core operations include documents.get (read full document content), documents.create (create new documents), and documents.batchUpdate (apply structured changes like text insertion, replacement, or formatting).

Prerequisites

  • A Google account or Google Workspace account with Google Docs access
  • Google Docs API enabled in Google Cloud Console (APIs & Services → Enable APIs → Google Docs API)
  • OAuth 2.0 credentials or a service account with appropriate scopes (https://www.googleapis.com/auth/documents or read-only scope)
  • A template Google Doc with placeholder strings if using the template replacement pattern
  • A Retool account with Resource creation permissions

Step-by-step guide

1

Enable Google Docs API and obtain OAuth credentials

Navigate to Google Cloud Console → APIs & Services → Library and search for Google Docs API. Click it and press Enable if it is not already active. For Retool integration, the recommended authentication approach is OAuth 2.0 with your personal Google account. In Google Cloud Console → APIs & Services → Credentials, click Create Credentials → OAuth client ID. Set the application type to Web application. In the Authorized redirect URIs section, add Retool's OAuth callback URL: https://oauth.retool.com/oauth/user/oauthcallback for Retool Cloud (or your self-hosted instance's equivalent URL: https://YOUR_DOMAIN/oauth/user/oauthcallback). Download or copy the Client ID and Client Secret from the credentials details. You will also need to configure the OAuth consent screen if it is not already set up — go to APIs & Services → OAuth consent screen, set User Type to Internal for Google Workspace accounts (this skips the app verification requirement), add the scope https://www.googleapis.com/auth/documents for full read/write access or https://www.googleapis.com/auth/documents.readonly for read-only. Save the consent screen configuration. For automated workflows using service accounts instead, create a service account, assign it the Editor role on specific Google Drive folders, and download the JSON key — then generate Bearer tokens using the same pattern as other Google Cloud APIs.

Pro tip: If you only need to read documents (not create or modify them), use the narrower scope https://www.googleapis.com/auth/documents.readonly — it requires less access and is easier to justify during OAuth consent screen review.

Expected result: Google Docs API is enabled in your Cloud project, and you have an OAuth 2.0 Client ID and Client Secret ready for the Retool Resource configuration.

2

Create the Google Docs REST API Resource in Retool

Navigate to the Resources tab in Retool's left sidebar and click Add Resource. Select REST API from the resource type list. Name the resource Google Docs API. In the Base URL field, enter https://docs.googleapis.com/v1. In the Authentication section, select OAuth 2.0 from the dropdown. Fill in the OAuth configuration fields: set Authorization URL to https://accounts.google.com/o/oauth2/auth, Token URL to https://oauth2.googleapis.com/token, enter your Client ID and Client Secret from the credentials you created, and set the Scope to https://www.googleapis.com/auth/documents (or space-separated if adding multiple scopes). Set the Access Token URL to the same token URL. Click Save Resource and then click the Connect button that appears to trigger the OAuth flow — Retool opens a Google sign-in popup where you authorize the app and grant the requested scopes. After successful authorization, the resource shows as connected with your account email. If multiple team members will use this resource, enable Share OAuth 2.0 credentials between users in the resource settings — this means your single authentication token is used for all Retool app users, which is appropriate for service-account-like access. Save the resource and verify it shows a Connected status.

Pro tip: The Google Docs API and Google Drive API have separate OAuth scopes. If you need to copy template documents (which requires Drive API to duplicate files), you will also need a Google Drive REST API Resource with scope https://www.googleapis.com/auth/drive — the Docs API alone cannot copy files.

Expected result: The Google Docs API REST Resource is saved in Retool with Connected status showing your Google account, and the Base URL is set to https://docs.googleapis.com/v1.

3

Read document content with a GET query

Open or create a Retool app and click + to create a new query in the Code panel. Select the Google Docs API resource. Set the HTTP method to GET and enter the path as /documents/DOCUMENT_ID — replace DOCUMENT_ID with the actual ID from your Google Doc's URL (the long alphanumeric string between /d/ and /edit in the URL, e.g., 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms). Click Run to execute the query. The Google Docs API returns a comprehensive JSON object representing the full document structure including the title, body (as a sequence of structural elements), lists, tables, and inline objects. The response is deeply nested: document.body.content is an array of StructuralElements, each of which can be a paragraph, table, sectionBreak, or tableOfContents. Paragraphs contain elements which contain textRun objects with the actual text content. Create a JavaScript transformer to extract readable text from this nested structure. Drag a Text component onto the canvas and bind it to the transformed output to display the document text. For a document management panel, also query the document title from document.title and display it as a heading.

docs_reader_transformer.js
1// Transformer: extract plain text from Google Docs API response
2function extractText(content) {
3 if (!content || !content.body || !content.body.content) return '';
4
5 return content.body.content
6 .filter(el => el.paragraph)
7 .map(el => {
8 return (el.paragraph.elements || [])
9 .filter(e => e.textRun)
10 .map(e => e.textRun.content)
11 .join('');
12 })
13 .join('')
14 .trim();
15}
16
17const plainText = extractText(data);
18return {
19 title: data.title || 'Untitled',
20 text: plainText,
21 word_count: plainText.split(/\s+/).filter(w => w.length > 0).length,
22 revision_id: data.revisionId
23};

Pro tip: The documentId in the URL follows the pattern: https://docs.google.com/document/d/{DOCUMENT_ID}/edit. Extract only the ID portion — do not include /edit or any query parameters.

Expected result: The query returns the full document JSON structure and the transformer extracts readable text. A Text component on the canvas displays the document title and content.

4

Create a new document from a Retool form

Create a form in Retool for document generation. Add Text Input components for the document title and key fields like client name, date, and project details. Add a Create Document button. Create a new query named createDocument, set the HTTP method to POST, and set the path to /documents. Set the body type to JSON and use the request body: { "title": "{{ titleInput.value }}" }. This creates a blank document with the specified title and returns the new document ID and URL. In the query's On Success event handler, add a second query called populateDocument. In populateDocument, set the method to POST and the path to /documents/{{ createDocument.data.documentId }}:batchUpdate. The batchUpdate body contains a requests array of operation objects. To insert text into the new document at position 1 (the beginning), use an insertText request with the full content built from your form fields. Structure the body as a JSON object with a requests array containing the desired text operations. After populating, display the document URL in a Text component: https://docs.google.com/document/d/{{ createDocument.data.documentId }}/edit — make this a clickable Link component so users can open the generated document directly from Retool.

batch_update_insert.json
1// batchUpdate request body for populating a new document
2// Set as the POST body for the /documents/{docId}:batchUpdate query
3{
4 "requests": [
5 {
6 "insertText": {
7 "location": { "index": 1 },
8 "text": "{{ titleInput.value }}\n\nPrepared for: {{ clientNameInput.value }}\nDate: {{ dateInput.value }}\n\n{{ scopeInput.value }}"
9 }
10 }
11 ]
12}

Pro tip: Google Docs positions are 1-indexed and include a position for every character, including newlines. When inserting text at position 1 (after the document start token), the text appears at the very beginning of the document body. Avoid inserting at index 0 as that is the document root token.

Expected result: Clicking Create Document in Retool creates a new Google Doc with the specified title and inserts the form content into the document body. A clickable link to the new document appears in the Retool app.

5

Implement template-based document generation with replaceAllText

The most powerful pattern for document generation is template replacement. Create a Google Doc template that contains placeholder strings in double braces like {{CLIENT_NAME}}, {{PROJECT_TITLE}}, {{TOTAL_VALUE}}, and {{START_DATE}}. Format the template with proper headings, tables, and styling — the API preserves all formatting during text replacement. Save the template document ID. In Retool, first create a Google Drive Resource (separate from the Docs Resource) with the scope https://www.googleapis.com/auth/drive to enable file copying. Create a query named copyTemplate using the Drive API: POST to https://www.googleapis.com/drive/v3/files/TEMPLATE_DOC_ID/copy with a JSON body containing { "name": "Proposal - {{ clientInput.value }}" }. This duplicates the template into the authenticated user's Drive. On success, use the returned id from the copy operation to run a batchUpdate on the new document. The batchUpdate body contains multiple replaceAllText requests — one for each placeholder — that swap placeholder strings with actual values from your Retool form and database queries. This approach is more reliable than manual text insertion because it maintains the template's exact formatting, fonts, table structures, and page layout. Add a Retool Workflow step to move the generated document to a specific shared Drive folder using the Drive API move endpoint for organized document storage.

template_replace.json
1// batchUpdate body for template placeholder replacement
2// Use this after copying the template document
3{
4 "requests": [
5 {
6 "replaceAllText": {
7 "containsText": { "text": "{{CLIENT_NAME}}", "matchCase": true },
8 "replaceText": "{{ clientInput.value }}"
9 }
10 },
11 {
12 "replaceAllText": {
13 "containsText": { "text": "{{PROJECT_TITLE}}", "matchCase": true },
14 "replaceText": "{{ projectInput.value }}"
15 }
16 },
17 {
18 "replaceAllText": {
19 "containsText": { "text": "{{TOTAL_VALUE}}", "matchCase": true },
20 "replaceText": "${{ valueInput.value }}"
21 }
22 },
23 {
24 "replaceAllText": {
25 "containsText": { "text": "{{START_DATE}}", "matchCase": true },
26 "replaceText": "{{ startDateInput.value }}"
27 }
28 },
29 {
30 "replaceAllText": {
31 "containsText": { "text": "{{GENERATED_DATE}}", "matchCase": true },
32 "replaceText": "{{ moment().format('MMMM D, YYYY') }}"
33 }
34 }
35 ]
36}

Pro tip: Use distinctive placeholder formats that are unlikely to appear naturally in document text — double braces {{PLACEHOLDER}} or custom delimiters like [[ ]] work well. Avoid single braces as they may conflict with Retool's own template syntax when constructing the query body.

Expected result: Submitting the Retool form copies the template document, replaces all placeholder strings with form and database values, and returns a link to a fully formatted, client-ready document — preserving all the template's original styling.

Common use cases

Sales proposal generator

Build a Retool form where sales reps enter deal details — client name, product selection, pricing tier, and scope — and click Generate Proposal. Retool queries your CRM for client history and pricing from your database, then calls the Google Docs API to duplicate a master proposal template and replace all placeholder strings with the actual values. The generated document URL is saved back to the CRM record and displayed to the rep as a clickable link. This eliminates an hour of manual document preparation per proposal.

Retool Prompt

Build a Retool form with fields for client name, deal value, product tier, and custom scope text. On form submission, query a PostgreSQL database for the client's previous purchases, then call the Google Docs API to copy a template document and replace placeholders like {{CLIENT_NAME}}, {{DEAL_VALUE}}, and {{SCOPE}} with the form and database values. Display the generated document URL in a Text component and save it to the CRM.

Copy this prompt to try it in Retool

Automated weekly team report

Create a Retool Workflow that runs on a Monday morning schedule, queries operational databases for the previous week's key metrics — support tickets closed, revenue, deploys shipped — and generates a formatted Google Docs weekly report using a template document. The workflow fills in all metric placeholders via batchUpdate, then shares the completed document with the team via a Slack notification containing the Doc URL. Team leads receive a formatted report without any manual data gathering.

Retool Prompt

Build a Retool Workflow triggered every Monday at 9 AM that queries PostgreSQL for last week's metrics (tickets resolved, new signups, revenue), copies a Google Docs weekly report template, uses batchUpdate to replace metric placeholders with the actual values, and sends the generated document URL to a Slack channel.

Copy this prompt to try it in Retool

Customer onboarding document builder

Build a Retool panel for customer success managers that auto-generates onboarding documents from a new customer record. When a CSM selects a new customer from a dropdown, Retool fetches their details from the CRM, their subscribed products from the product database, and their assigned CSM contacts. A Generate Onboarding Doc button creates a personalized welcome document, implementation checklist, and contact list using the Google Docs template system. The document is stored in a shared Google Drive folder for the customer.

Retool Prompt

Build a Retool app where a CSM selects a customer from a dropdown, sees a preview of their account details from Salesforce, and clicks a button that generates a personalized onboarding document in Google Docs by replacing template placeholders with the customer's name, subscribed products, and assigned contacts. Show the resulting document link in the app.

Copy this prompt to try it in Retool

Troubleshooting

API returns 403 Forbidden with 'Request had insufficient authentication scopes'

Cause: The OAuth token was granted narrower scopes than the API call requires. For example, the read-only scope was granted but a write operation (batchUpdate or create) is being attempted.

Solution: Delete and recreate the Retool Resource's OAuth connection to re-request scopes. In the Resource settings, update the Scope field to include https://www.googleapis.com/auth/documents (not readonly). Click the Connect button again to re-authorize with the correct scopes. If using a service account, verify the service account has Editor access to the specific document or Drive folder.

batchUpdate returns 400 with 'Invalid requests[0].insertText: Invalid location'

Cause: The insertText request specifies an index that is out of bounds for the current document. A new blank document has very few valid positions (typically only index 1), and inserting at index 0 or beyond the document length causes this error.

Solution: Always insert text at index 1 for new documents. For inserting into specific locations in existing documents, first call documents.get to retrieve the current document structure and identify valid paragraph end indices. Avoid hardcoding position indices for documents whose content may change.

typescript
1// Correct: insert at position 1 for new documents
2{
3 "insertText": {
4 "location": { "index": 1 },
5 "text": "Your content here"
6 }
7}

Template replaceAllText operations complete with 200 but placeholders are not replaced in the document

Cause: The placeholder text in the template contains smart quotes, invisible Unicode characters, or the text was split across multiple textRun elements by Google Docs' internal formatting, preventing exact string matching.

Solution: Open the template document and retype the placeholder text manually rather than pasting it. Check that matchCase in the replaceAllText request matches the exact casing in the template. Use the documents.get API to retrieve the template document's raw text and confirm the placeholder appears as a single string in a textRun.content field — if it appears split across multiple textRun elements, delete and retype it in the document.

Drive API copy request returns 'File not found' for the template document ID

Cause: The service account or OAuth user does not have access to the template document in Google Drive. Drive API file operations require explicit sharing permissions, not just API scope authorization.

Solution: Open the template document in Google Drive and share it with the service account email (from the service account JSON key) or confirm the OAuth user has at least Viewer access. For service account access, check the sharing settings of both the template file and the parent folder. Alternatively, move the template to a shared Drive folder that the service account has access to.

Best practices

  • Create a dedicated template document for each document type you generate and keep it in a restricted Google Drive folder that only your automation service account can access — prevent accidental template modification.
  • Use replaceAllText with unique placeholder delimiters ({{PLACEHOLDER}}) rather than insertText at positions — position-based insertion breaks whenever the template document structure changes.
  • Store the template document ID in a Retool configuration variable rather than hardcoding it in queries — this makes template updates a configuration change rather than a code change.
  • Combine Google Docs and Google Drive REST API Resources in the same Retool app: Docs for content operations, Drive for file management (copy, move, share) — they require separate resources with different base URLs.
  • Add a confirmation step before generating documents that shows a preview summary of the data being used — this catches errors before document creation rather than after.
  • For high-volume document generation (more than 10 documents per minute), use Retool Workflows instead of app-level queries to queue operations and respect Google API rate limits.
  • Save the generated document URL back to your database using an upsert query immediately after generation — this creates an audit trail and prevents accidental duplicate document creation.

Alternatives

Frequently asked questions

Can Retool read the content of private Google Docs that require sign-in?

Yes, as long as the Google account authenticated with the Retool REST API Resource has at least Viewer access to the document. The OAuth flow grants Retool the ability to read documents accessible to the authenticated account. For service account access, the document must be explicitly shared with the service account email address. Documents that require organizational domain sign-in (Google Workspace restricted documents) can be accessed if the service account is in the same Workspace organization.

Is there a limit to how many placeholder replacements I can do in a single batchUpdate?

Yes. The Google Docs API accepts a maximum of 200 requests per batchUpdate call. Each replaceAllText operation counts as one request, so you can replace up to 200 placeholders in a single call. For documents with more replacements, split them into multiple batchUpdate calls chained in a Retool Workflow. In practice, most document templates have far fewer than 200 unique placeholders.

Can I add images, tables, or formatted sections to a generated Google Doc from Retool?

Yes, but with complexity. The batchUpdate API supports insertInlineImage (from a public URL), insertTable, insertTableRow, and paragraph style operations. However, constructing these requests requires knowing specific document positions (indices), which change as content is inserted. The most practical approach for complex formatting is to build rich structure into the template document and use replaceAllText for data substitution — the API preserves all existing formatting while replacing placeholder text.

How do I delete or archive generated documents from Retool?

Deleting Google Docs requires the Google Drive API (not the Docs API) with the drive.files.delete endpoint. Create a separate Google Drive REST API Resource in Retool with the scope https://www.googleapis.com/auth/drive and use DELETE /files/{fileId} to permanently delete a document or PATCH /files/{fileId} with trashed: true to move it to trash. Add a confirmation modal in Retool before triggering delete operations to prevent accidental document loss.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Integrations are where projects stall

We wire Retool integrations like this one every week — auth, webhooks, edge cases included. Fixed-price builds from $13K, delivered in 6–10 weeks.

Talk to an integration engineer

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.