How to Sync Google Sheets to PostgreSQL with Python & n8n

Step-by-step guide to automate data sync from Google Sheets to PostgreSQL using a Python script and an n8n workflow—no manual export needed.

How to Sync Google Sheets to PostgreSQL with Python & n8n - Technology Tutorials
Short answer: Use a small Python automation script that reads a Google Sheet via the Sheets API and upserts rows into PostgreSQL, then trigger that script from an n8n workflow that can be scheduled, monitored, and extended with error handling.

Many teams keep lightweight data in Google Sheets because it is easy for non‑technical users to edit. When that data needs to be queried, reported, or joined with other systems, a relational database such as PostgreSQL is a better fit. The challenge is keeping the sheet and the database in sync without manual exports.

This guide shows you how to build a reliable, schedule‑able pipeline that combines a reusable python automation script with an n8n workflow. By the end of the tutorial you will have:

  • A Python module that authenticates to Google, reads a sheet, and upserts rows into PostgreSQL.
  • An n8n workflow that runs the script on a cron‑like schedule, captures logs, and notifies on failure.
  • Tips for handling schema changes, large sheets, and rate‑limit errors.

What You'll Learn

  • How to set up Google Service Account credentials for API access.
  • How to write a clean, testable Python script that maps sheet columns to PostgreSQL columns.
  • How to containerise the script (optional) and expose it to n8n.
  • How to configure n8n nodes: HTTP Request, Execute Command, and Error Workflow.
  • Best practices for idempotent syncs and troubleshooting.

Prerequisites

  • Python 3.11+ installed locally or in a CI environment.
  • Access to a PostgreSQL instance (cloud or on‑prem). The guide uses postgres:16 (current stable version per the official release notes).
  • n8n version 1.0+ (the open‑source self‑hosted edition; see the installation guide).
  • Basic familiarity with pip, virtual environments, and SQL.

Create a Google Service Account & enable the Sheets API

  1. Open the Google Cloud Console and create a new project (or reuse an existing one).
  2. Navigate to **APIs & Services → Library** and enable Google Sheets API.
  3. Go to **APIs & Services → Credentials**, click **Create credentials → Service account**.
  4. Give the service account a name such as n8n-sheet-sync. Grant the role Viewer on the project (no write access needed for Sheets API).
  5. After creation, click **Add Key → Create new key** → JSON. Download the JSON file; it will be referenced as service_account.json later.
  6. Share the target Google Sheet with the service account’s email address (found in the JSON file) using the normal **Share** dialog and give it **Viewer** or **Editor** rights.

Prepare PostgreSQL for the sync

Assume a sheet with columns id, name, email, signup_date. Create a matching table:

CREATE TABLE public.contacts (
    id           BIGINT PRIMARY KEY,
    name         TEXT NOT NULL,
    email        TEXT UNIQUE NOT NULL,
    signup_date  DATE
);

If you prefer to let the script create the table automatically, add a CREATE TABLE IF NOT EXISTS block in the Python code (see later).

Write the Python automation script

The script is deliberately split into three functions so that it can be imported as a library or executed directly.

#!/usr/bin/env python3
import os
import json
import logging
from datetime import datetime
from typing import List, Dict

import psycopg2
from google.oauth2 import service_account
from googleapiclient.discovery import build

# ----------------------------------------------------------------------
# Configuration (environment variables are preferred for CI/CD)
# ----------------------------------------------------------------------
SHEET_ID = os.getenv("GOOGLE_SHEET_ID")
RANGE_NAME = os.getenv("GOOGLE_SHEET_RANGE", "Sheet1!A:D")
PG_DSN = os.getenv("POSTGRES_DSN")  # e.g. postgresql://user:pass@host:5432/db
SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
SERVICE_ACCOUNT_FILE = os.getenv("GOOGLE_APPLICATION_CREDENTIALS", "service_account.json")

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

# ----------------------------------------------------------------------
def get_sheet_values() -> List[List]:
    """Fetch raw values from the Google Sheet."""
    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES
    )
    service = build("sheets", "v4", credentials=credentials, cache_discovery=False)
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SHEET_ID, range=RANGE_NAME).execute()
    values = result.get("values", [])
    if not values:
        logging.warning("No data found in the sheet.")
    return values

# ----------------------------------------------------------------------
def rows_to_dicts(rows: List[List]) -> List[Dict]:
    """Convert rows (including header) to a list of dicts."""
    if not rows:
        return []
    header = [h.strip().lower() for h in rows[0]]
    data = []
    for row in rows[1:]:
        # Pad missing columns with None
        row += [None] * (len(header) - len(row))
        record = dict(zip(header, row))
        # Cast types where appropriate
        if "id" in record and record["id"]:
            record["id"] = int(record["id"])
        if "signup_date" in record and record["signup_date"]:
            try:
                record["signup_date"] = datetime.strptime(
                    record["signup_date"], "%Y-%m-%d"
                ).date()
            except ValueError:
                record["signup_date"] = None
        data.append(record)
    return data

# ----------------------------------------------------------------------
def upsert_contacts(conn, contacts: List[Dict]):
    """Insert new rows or update existing ones based on the primary key."""
    with conn.cursor() as cur:
        for rec in contacts:
            cur.execute(
                """
                INSERT INTO public.contacts (id, name, email, signup_date)
                VALUES (%s, %s, %s, %s)
                ON CONFLICT (id) DO UPDATE SET
                    name = EXCLUDED.name,
                    email = EXCLUDED.email,
                    signup_date = EXCLUDED.signup_date;
                """,
                (
                    rec.get("id"),
                    rec.get("name"),
                    rec.get("email"),
                    rec.get("signup_date"),
                ),
            )
    conn.commit()
    logging.info(f"Upserted {len(contacts)} rows into PostgreSQL.")

# ----------------------------------------------------------------------
def main():
    logging.info("Starting Google Sheets → PostgreSQL sync")
    raw_rows = get_sheet_values()
    contacts = rows_to_dicts(raw_rows)

    if not contacts:
        logging.info("No rows to process – exiting.")
        return

    conn = psycopg2.connect(dsn=PG_DSN)
    try:
        upsert_contacts(conn, contacts)
    finally:
        conn.close()
    logging.info("Sync completed successfully.")

# ----------------------------------------------------------------------
if __name__ == "__main__":
    main()

Key points:

  • All secrets are read from environment variables – this matches n8n’s Credentials system and keeps the script portable.
  • The ON CONFLICT (id) clause makes the operation idempotent, so repeated runs do not create duplicates.
  • Type conversion is minimal; adapt the rows_to_dicts function if your sheet contains more complex data.

Pro Tip: Store the script in a private Git repository and version it with semantic tags. n8n can pull a specific tag each run, guaranteeing reproducibility.

Optional: Dockerise the script

If you prefer to keep the runtime isolated from the n8n host, build a lightweight container. Use the official python:3.11-slim image to keep the footprint under 150 MB.

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY sync_sheet.py .

# The entrypoint expects the same env vars as the script.
ENTRYPOINT ["python", "sync_sheet.py"]

Generate requirements.txt with:

google-api-python-client==2.135.0
google-auth==2.30.0
psycopg2-binary==2.9.9

Build and push the image to your container registry (Docker Hub, GitHub Packages, etc.). n8n can then invoke the container via the **Execute Command** node or the **Docker** node (available in the community nodes collection).

Build the n8n workflow

  1. Open n8n, create a new workflow, and give it a descriptive name (e.g., “Sync Google Sheet → PostgreSQL”).
  2. Add a **Cron** trigger node:
    • Set the schedule to your desired frequency (e.g., every 15 minutes).
  3. Add an **Execute Command** node (or **Docker** node if you built an image). Configure:
    • Command: python /path/to/sync_sheet.py (or docker run …).
    • Environment variables:
      GOOGLE_SHEET_ID={{$env.GOOGLE_SHEET_ID}}
      GOOGLE_SHEET_RANGE=Sheet1!A:D
      POSTGRES_DSN={{$env.POSTGRES_DSN}}
      GOOGLE_APPLICATION_CREDENTIALS=/data/service_account.json
    • Upload the service_account.json file via the **Binary Data** field or mount it from a secret store.
  4. Add an **Error Workflow** (via the workflow settings) that sends a Slack or email notification when the command returns a non‑zero exit code. Use the built‑in **Slack** or **Email** nodes.
  5. Connect the nodes: Cron → Execute Command → (optional) Success Message node.
  6. Save and activate the workflow.

n8n stores each execution in its UI, so you can review logs, retry failed runs, and add branching logic later (e.g., only run when the sheet has changed – see the “ETag” field in the Sheets API response).

Testing & monitoring

  • Local test: Run the script manually with a test sheet and a local PostgreSQL container. Verify that rows are inserted and updated as expected.
  • Dry‑run mode: Add a --dry-run flag that prints the generated SQL without executing it. This helps during schema changes.
  • n8n execution logs: In the n8n UI, click an execution to see stdout/stderr. Configure the **Execute Command** node to capture both streams.
  • Metrics: Use PostgreSQL’s pg_stat_activity view or a monitoring tool (e.g., Prometheus + Grafana) to watch the number of inserts/updates per run.

Common pitfalls & how to avoid them

Issue Typical cause Fix
Authentication error “Invalid Credentials” Service account JSON not found or not shared with the sheet Confirm the path in GOOGLE_APPLICATION_CREDENTIALS and re‑share the sheet with the service‑account email.
Rate‑limit (429) from Sheets API Too many reads in a short period (e.g., every minute on a large sheet) Increase the cron interval, or implement exponential back‑off using the googleapiclient retry settings.
Duplicate rows in PostgreSQL Primary key not defined or mismatched column names Ensure the id column is primary key and that the script maps the same column name.
Data type errors (e.g., “invalid input syntax for type date”) Sheet contains malformed dates Validate/clean dates in rows_to_dicts or add a fallback to NULL.
n8n “Command not found” Python not in PATH inside the n8n container Install Python in the n8n host or use the Docker node to run the script in its own image.

Next steps

  • Implement change detection: store the sheet’s ETag in a tiny key‑value table and skip the upsert when the tag hasn’t changed.
  • Extend the workflow with a **Webhook** node so that non‑technical users can trigger an immediate sync from a Google Form.
  • Secure the PostgreSQL connection using SSL certificates; n8n supports TLS‑encrypted credentials.
  • Package the Python code as a pip‑installable library for reuse across multiple sheets.

Frequently Asked Questions

Can I sync multiple sheets with the same workflow?

Yes. Add a **Set** node before the Execute Command to change GOOGLE_SHEET_ID and RANGE_NAME for each sheet, then use a **SplitInBatches** node to iterate over a list of sheet IDs.

Do I need to enable Google Drive API as well?

No. The Sheets API alone is sufficient for reading cell values. Only when you need to create or move files would the Drive API be required.

How large a sheet can this approach handle?

The Sheets API returns a maximum of 10 MB per request. For very large datasets, consider paging with the majorDimension and pageToken parameters, or export the sheet as CSV and stream it into PostgreSQL.

Is the script safe for production?

It is idempotent, uses parameterised queries (preventing SQL injection), and reads credentials from environment variables. For production you should also add:

  • Structured logging (e.g., JSON) for log aggregation.
  • Retry logic around the API call.
  • Secrets management (HashiCorp Vault, AWS Secrets Manager, etc.) instead of plain env vars.

Can I run the sync on a serverless platform instead of n8n?

Yes. The same script can be deployed as an AWS Lambda function, Google Cloud Run, or Azure Function. n8n merely provides a visual scheduler; replace it with the platform’s native scheduler if you prefer.

Official documentation