# Google Sheets Sync: Append, Upsert, Replace & Read (`khanjankavani/google-sheets-sync`) Actor

Send any Apify dataset, JSON or CSV to Google Sheets, or read a sheet back. Upsert by key, skip duplicates, auto-add new columns, retry Google rate limits, and get errors in plain English. Ideal as an integration after any scraper.

- **URL**: https://apify.com/khanjankavani/google-sheets-sync.md
- **Developed by:** [Khanjan Kavani](https://apify.com/khanjankavani) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.15 / 1,000 row written to google sheets

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Google Sheets Sync: Append, Upsert, Replace & Read

Send any Apify dataset, JSON or CSV into Google Sheets, or read a sheet back into a dataset. Built to just work on big, repeated runs: it updates the right rows, skips duplicates, adds new columns by itself, and waits out Google's rate limits instead of failing.

### What it does

| Mode | What happens | Typical use |
|---|---|---|
| **Append** | Adds rows at the bottom. With key columns, rows already in the sheet are skipped. | Daily scraper results into one growing sheet, without duplicates |
| **Upsert** | Updates rows whose key already exists, adds the rest. | Price or stock tracking: one row per product, always current |
| **Replace** | Clears the tab and writes fresh data. | A dashboard tab that always shows the latest run |
| **Read** | Copies the tab into this run's dataset. | Use a sheet as the input list for another Actor |

**Try it free first:** run it with the spreadsheet and key left empty. You get a preview of exactly how your rows and columns will look in Sheets (nothing is written, no rows are charged).

### Why people switch to it

- **Doesn't fall over on big data.** Writes in chunks of 2,000 rows and retries automatically when Google says "too many requests" (HTTP 429) or has a hiccup (5xx).
- **Upsert by any key.** One or more key columns (`url`, `sku`, `id`…). Matching ignores case and extra spaces, and blank rows in your sheet don't break row positions.
- **New fields? New columns.** If your data gains a field, a column is added at the end. Your existing columns and their order stay as they are.
- **Nested data becomes readable.** `{"address": {"city": "Surat"}}` becomes a column `address.city`. Lists of words become `a, b, c`.
- **Errors in plain English.** Instead of a stack trace you get, for example: *"Open the sheet, click Share, and add sync-bot@your-project.iam.gserviceaccount.com as Editor."*
- **Creates the tab for you** if it doesn't exist yet.

### Setup (once, about 5 minutes)

1. Open [Google Cloud console](https://console.cloud.google.com/), create a project (free), and enable **Google Sheets API**.
2. Go to **IAM & Admin → Service accounts → Create service account**. No roles are needed.
3. Open the service account → **Keys → Add key → JSON**. A file downloads.
4. Open that file, copy everything, and paste it into **Service account JSON key** (stored encrypted by Apify).
5. Open your Google Sheet → **Share** → add the service account's email (it ends in `iam.gserviceaccount.com`) as **Editor**.

### Run it after another Actor automatically

In your scraper's **Integrations** tab, add "Run Actor" → *Google Sheets Sync* and set:

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/your-sheet-id/edit",
  "tab": "Results",
  "mode": "upsert",
  "keyColumns": ["url"],
  "datasetId": "{{resource.defaultDatasetId}}",
  "serviceAccountKey": "paste once in the integration settings"
}
```

Every time the scraper finishes, the sheet updates itself.

### Input

| Field | Required | Notes |
|---|---|---|
| `spreadsheet` | to write | Sheet URL or ID (leave empty with the key for a free preview) |
| `serviceAccountKey` | to write | Full JSON key of a service account (secret) |
| `mode` | no | `append` (default), `upsert`, `replace`, `read` |
| `tab` | no | Tab name; created if missing; empty = first tab |
| `keyColumns` | for upsert | e.g. `["url"]` |
| `datasetId` / `rawData` / `dataUrl` | one of them | Apify dataset, JSON array, or link to JSON/CSV |
| `columns` | no | Columns to put first, in order |
| `flatten` | no | Default `true` |
| `parseValues` | no | Default `true` (Sheets turns `12.5` into a number, dates into dates) |
| `maxItems` | no | Limit rows |

### Output

The run's key-value store `OUTPUT` record holds a summary, for example:

```json
{ "mode": "upsert", "written": 1840, "updated": 1702, "appended": 138, "columns": 14, "tab": "Results",
  "spreadsheetUrl": "https://docs.google.com/spreadsheets/d/.../edit#gid=0" }
```

In **read** mode, the rows go into the run's dataset (one item per row, header names as keys).

### Pricing

You pay per row written or read, plus $0.001 per run (see the Pricing tab). Skipped duplicates and preview runs have no row charges.

### Limits to know

- Google Sheets holds up to 10 million cells per spreadsheet. The Actor tells you clearly if a write would pass it.
- A cell holds up to 50,000 characters; longer text is cut and marked `…[cut]`.
- Upsert reads the whole tab first, so very large tabs (over ~200,000 rows) take longer.

### FAQ

**Do I need OAuth or a Google login?** No. A service account key is more reliable for automation: it never expires like a login token does.

**Is my key safe?** The field is marked secret, so Apify stores it encrypted and hides it in logs.

**Can I use Excel?** Upload the Excel file to Google Drive and open it as a Google Sheet, then use its link.

Questions or a missing feature? Open an issue on this Actor's Issues tab. We answer within 2 working days.

# Actor input Schema

## `spreadsheet` (type: `string`):

Paste the Google Sheets link. Share the sheet with your service account email as Editor first. Leave this and the key empty to see a free preview of how your data will look.

## `tab` (type: `string`):

Sheet tab to use. Created automatically if it doesn't exist. Empty = first tab.

## `mode` (type: `string`):

Append adds rows at the bottom (with key columns it skips rows already in the sheet). Upsert updates matching rows and adds the rest. Replace clears the tab and writes fresh data. Read copies the tab into this run's dataset.

## `keyColumns` (type: `array`):

Columns that identify a row, e.g. url or id. Used by upsert and to skip duplicates in append.

## `serviceAccountKey` (type: `string`):

Paste the whole JSON key file of a Google Cloud service account with the Google Sheets API enabled. Stored encrypted.

## `datasetId` (type: `string`):

Data source: an Apify dataset (for example the default dataset of a scraper run). In an integration use {{resource.defaultDatasetId}}.

## `rawData` (type: `array`):

Data source: a JSON array of objects. Used if no dataset ID is given.

## `dataUrl` (type: `string`):

Data source: a public link to a JSON array or a CSV file.

## `columns` (type: `array`):

Optional: columns to put first, in this order. Other columns follow.

## `flatten` (type: `boolean`):

Turn nested objects into columns like address.city.

## `parseValues` (type: `boolean`):

On: 12.5 becomes a number, 2026-11-14 a date. Off: everything is stored as text.

## `maxItems` (type: `integer`):

Optional limit on how many rows to write or read.

## Actor input object example

```json
{
  "mode": "append",
  "flatten": true,
  "parseValues": true
}
```

# Actor output Schema

## `summary` (type: `string`):

No description

## `rows` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "flatten": true,
    "parseValues": true
};

// Run the Actor and wait for it to finish
const run = await client.actor("khanjankavani/google-sheets-sync").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "flatten": True,
    "parseValues": True,
}

# Run the Actor and wait for it to finish
run = client.actor("khanjankavani/google-sheets-sync").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "flatten": true,
  "parseValues": true
}' |
apify call khanjankavani/google-sheets-sync --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,khanjankavani/google-sheets-sync"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/FiiL4hRCuYf40mn2X/builds/QMHyXKSHG04PELD59/openapi.json
