# Google Sheets Sync: Reliable Import & Export (`1coastmedia/google-sheets-sync`) Actor

Send any Apify dataset or JSON to Google Sheets (append with dedupe, or safe replace), or export a sheet to a dataset. Retries Google rate limits, chunks big imports, never wipes your sheet on an empty run.

- **URL**: https://apify.com/1coastmedia/google-sheets-sync.md
- **Developed by:** [Blake Daniels](https://apify.com/1coastmedia) (community)
- **Categories:** Integrations, Developer tools
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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: Reliable Import & Export

Send any Apify dataset (or plain JSON) to a Google Sheet, or export a sheet to a dataset.
Built for scheduled pipelines that must not break: it retries Google's rate limits, splits
big imports into safe chunks, and never wipes your sheet because an upstream run came back empty.

### What it does

| Mode | What happens |
|---|---|
| **append** (default) | Adds rows below the data already in the sheet. New fields become new columns on the right; existing columns never move. Optional **deduplicate by** columns skip rows that are already there, so reruns don't double up. |
| **replace** | Overwrites the tab. New data is written first and leftovers are cleared after, so a failure never leaves you with an empty sheet. Refuses to run with zero items unless you allow it. |
| **read** | Exports the tab to this run's dataset (first row = column names). |

Nested objects are flattened the same way as Apify's CSV export (`address/city`, `tags/0`).

### Why runs don't fail

- **Rate limits:** Google allows about 60 writes per minute per user. 429s and 5xx errors are retried with backoff (honouring `Retry-After`) instead of failing the run.
- **Big imports:** rows go in chunks (max 5,000 rows or about 1.5 MB per request). Append mode never rewrites the whole sheet, it only adds rows.
- **Limits checked first:** if an import would pass Google's 10 million cell limit, the run stops *before* writing anything and says so.
- **Credentials that don't expire:** use a service account key (recommended) or an OAuth refresh token. Nothing depends on a browser login that times out.
- **Errors you can act on:** "Share the spreadsheet with bot@project.iam.gserviceaccount.com as an Editor", "The Google Sheets API is not enabled for this project", "Sheet 'Leads' not found. Sheets in this spreadsheet: ...".
- **Safe by default:** values are written exactly as given (`RAW`), so scraped text starting with `=` can never run as a formula. Turn on **parseValues** if you want Google to parse dates and formulas.

### Setup (about 3 minutes, once)

1. In [Google Cloud Console](https://console.cloud.google.com/), create a project (or pick one) and enable the **Google Sheets API**.
2. *IAM & Admin → Service accounts → Create*. Open it, *Keys → Add key → JSON*. A key file downloads.
3. Open your spreadsheet, click **Share**, and add the service account's `client_email` (from the key file) as **Editor**.
4. Paste the whole key file into **Google service account key** in this actor's input.

### Use it after another actor

Add this actor as an **integration** on any actor or task (*Integrations → Apify actor*). It
picks up the dataset of the run that just finished, so you don't need to set `datasetId`.
With **append** + **deduplicate by** (for example `url`), a daily scraper keeps one growing,
duplicate-free sheet.

### Input example

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Leads",
  "mode": "append",
  "datasetId": "aBcD1234",
  "deduplicateBy": ["url"],
  "serviceAccountKey": "{ ...paste key JSON... }"
}
```

### Output

Each run stores a summary as `OUTPUT` in the key-value store (see `sample-output.json`):
rows written or read, duplicates skipped, columns, cells truncated at Google's 50,000
character limit, and the number of Google API requests. Read mode also fills the dataset.

### Pricing

Pay per event: you pay per row written or read (`row-written`, `row-read`). No monthly rental.

### Limits

- 10 million cells per spreadsheet and 50,000 characters per cell (Google's limits).
- Append dedupe reads the existing sheet once per run, which is fast for sheets up to a few hundred thousand rows.

# Actor input Schema

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

Paste the spreadsheet URL (https://docs.google.com/spreadsheets/d/...) or just its ID.

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

append: add rows below existing data. replace: overwrite the sheet (writes first, then clears leftovers). read: export the sheet to this run's dataset.

## `sheetName` (type: `string`):

Tab to use. Empty = the first tab. For append/replace a missing tab is created.

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

Apify dataset to import. Not needed when this actor runs as an integration after another actor: it then uses that run's dataset.

## `items` (type: `array`):

Items to import directly instead of a dataset.

## `deduplicateBy` (type: `array`):

Append mode: skip items whose values in these columns already exist in the sheet. Makes scheduled reruns safe (no double rows).

## `columnsOrder` (type: `array`):

Columns to put first, in this order. Others follow in first-seen order. Existing sheet columns never move.

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

Recommended. Paste the full JSON key of a Google Cloud service account, then share your spreadsheet with its client_email as Editor. Never expires, so schedules keep working.

## `oauthClientId` (type: `string`):

Use with client secret and refresh token instead of a service account.

## `oauthClientSecret` (type: `string`):

OAuth client secret.

## `oauthRefreshToken` (type: `string`):

Refresh token with the spreadsheets scope.

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

Off (default): values are stored exactly as given, so a scraped '=...' can never run as a formula. On: Google parses them like typed input.

## `allowEmptyReplace` (type: `boolean`):

By default an empty upstream run will not wipe your sheet in replace mode.

## `createSheetIfMissing` (type: `boolean`):

Append/replace only.

## `flattenSeparator` (type: `string`):

Nested objects become columns like address/city.

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

Import at most this many dataset items.

## Actor input object example

```json
{
  "mode": "append",
  "parseValues": false,
  "allowEmptyReplace": false,
  "createSheetIfMissing": true,
  "flattenSeparator": "/"
}
```

# Actor output Schema

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

ok, mode, sheet, rowsWritten, rowsRead, duplicatesSkipped, truncatedCells, columns, durationMs, googleRequests, or error if the run failed.

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

One dataset item per sheet row; the first row of the sheet gives the field names. Empty in append and replace modes.

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("1coastmedia/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 = {}

# Run the Actor and wait for it to finish
run = client.actor("1coastmedia/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 '{}' |
apify call 1coastmedia/google-sheets-sync --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,1coastmedia/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/WoBYJxjd5tvWIgo6X/builds/P1in9SDZdNgqD2TOV/openapi.json
