How to Use Google Workspace Docs API to Automate Invoice Generation

For many small businesses and freelancers, generating monthly invoices involves opening a previous Google Doc, making a copy, manually deleting the old client’s name, typing in the new line items, calculating the total, and saving it as a PDF. This manual process is tedious and prone to embarrassing copy-paste errors—like sending a bill to Client A that accidentally contains Client B’s address. To eliminate this risk and save hours of administrative work, you can programmatically generate perfect, customized documents using the Google Workspace Docs API.

The Concept: Template Replacement

The most efficient way to automate document creation is not to write code that builds a document from scratch, paragraph by paragraph. Instead, you create a beautifully formatted “Template” document manually in the Google Docs UI. Wherever variable data should go, you insert a unique text tag, like {{CLIENT_NAME}} or {{TOTAL_AMOUNT}}.

Your Python script will then use the Drive API to duplicate the template, and the Docs API to perform a massive “Find and Replace” operation on the tags.

Step 1: Create the Template

  1. Create a new Google Doc and design your invoice.
  2. Add your logo, company address, and static payment terms.
  3. Insert the tags exactly as you want to replace them:
    • Bill To: {{CLIENT_NAME}}
    • Date: {{DATE}}
    • Services: {{SERVICES_DESC}}
    • Total Due: {{TOTAL_AMOUNT}}
  4. Note the Document ID from the URL (the long string of characters between /d/ and /edit).

Step 2: Copy the Template (Drive API)

Because you never want to overwrite your master template, your script must first copy it. This requires the Google Drive API.

# Assuming 'drive_service' is your authenticated Drive API client
template_id = '1aB2c3D4e5F6g7H8i9J0'

copy_metadata = {
    'name': 'Invoice - ACME Corp - October 2024'
}

copied_file = drive_service.files().copy(
    fileId=template_id, 
    body=copy_metadata
).execute()

new_document_id = copied_file['id']
print(f"Created new document with ID: {new_document_id}")

Step 3: Prepare the Replacement Requests (Docs API)

Now that you have a fresh copy, you use the Google Docs API to modify it. The Docs API uses a batchUpdate method, which allows you to send multiple formatting or replacement commands in a single network request.

We will construct an array of replaceAllText requests based on our client data.

# The dynamic data (this could come from a database or a CRM)
invoice_data = {
    '{{CLIENT_NAME}}': 'ACME Corporation',
    '{{DATE}}': 'October 1, 2024',
    '{{SERVICES_DESC}}': 'Web Hosting and Maintenance (Sept 2024)',
    '{{TOTAL_AMOUNT}}': '$1,500.00'
}

requests = []

# Build a request for every key in the dictionary
for tag, value in invoice_data.items():
    requests.append({
        'replaceAllText': {
            'containsText': {
                'text': tag,
                'matchCase': True
            },
            'replaceText': value
        }
    })

Step 4: Execute the Batch Update

Send the array of requests to the newly copied document.

# Assuming 'docs_service' is your authenticated Docs API client
result = docs_service.documents().batchUpdate(
    documentId=new_document_id, 
    body={'requests': requests}
).execute()

print("Invoice populated successfully.")

When this code executes, the Google Doc is instantly updated. Because it’s a batch update, it happens almost instantaneously on Google’s servers.

Step 5: Export to PDF (Optional but Recommended)

You rarely send a raw Google Doc to a client, as they could edit the total amount. To finish the automation, you can use the Drive API to immediately export the finished document as a PDF, ready to be attached to an email.

request = drive_service.files().export_media(
    fileId=new_document_id, 
    mimeType='application/pdf'
)

with open('Invoice_ACME_Oct.pdf', 'wb') as f:
    f.write(request.execute())

By combining the Drive API for file manipulation and the Docs API for text replacement, you can hook this script into your billing software or a Google Form, generating hundreds of customized, professional PDFs in seconds.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.