> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zapier.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Call apps from a Next Gen Zap written in code

> Call your connected apps from a workflow written with the @zapier/zapier-durable package: point each step at a connection, test it on your machine, and publish it to Zapier with those connections. The example uses Gmail and Google Sheets.

Steps in a workflow can run actions in any of 10,000+ apps through the Zapier SDK. In this guide, you build a workflow that welcomes a new customer: it saves them to Google Sheets, sends a welcome email from Gmail, waits, and sends a follow-up email. Like the quick start, the workflow has no trigger, so it runs only when you start it.

## Before you begin

* Complete the [quick start](https://docs.zapier.com/sdk/build-a-zap-in-code.md). This guide uses the same project, login, and `ZAPIER_STABILITY=beta` setting.
* A Google Sheet with the column headings `Name`, `Email`, and `Signed up` in row 1.

## 1. Write a workflow that uses your apps

Replace the contents of `workflow.ts` with this workflow:

```typescript workflow.ts theme={null}
import { defineDurable } from "@zapier/zapier-durable";
import { createZapierSdk } from "@zapier/zapier-sdk";
import { z } from "zod";

const SPREADSHEET_ID = "YOUR_SPREADSHEET_ID";

// Create the client outside run: code in run that is not inside a step cannot read the clock.
const zapier = createZapierSdk();

export default defineDurable({
  name: "onboard-customer",
  description: "Saves a new customer to Google Sheets, sends a welcome email, waits, then sends tips.",
  inputSchema: z.object({ name: z.string(), email: z.string() }),
  run: async (ctx, input) => {
    await ctx.step("save-customer", async () => {
      const { data } = await zapier.runAction({
        app: "google-sheets",
        actionType: "write",
        action: "add_row",
        connection: "sheets",
        inputs: {
          spreadsheet: SPREADSHEET_ID,
          worksheet: "0",
          "COL$A": input.name,
          "COL$B": input.email,
          "COL$C": new Date().toISOString(),
        },
      });
      return data;
    });

    await ctx.step({
      name: "send-welcome",
      maxAttempts: 3,
      retryDelaySeconds: 2,
      run: async () => {
        const { data } = await zapier.runAction({
          app: "gmail",
          actionType: "write",
          action: "message",
          connection: "gmail",
          inputs: {
            to: input.email,
            subject: `Welcome, ${input.name}!`,
            body: "Thanks for signing up. Your first tips arrive shortly.",
          },
        });
        return data;
      },
    });

    await ctx.wait("wait-before-tips", 5);

    await ctx.step("send-tips", async () => {
      const { data } = await zapier.runAction({
        app: "gmail",
        actionType: "write",
        action: "message",
        connection: "gmail",
        inputs: {
          to: input.email,
          subject: "3 tips to get started",
          body: "1. Connect your apps. 2. Build your first Zap. 3. Check your Zap runs.",
        },
      });
      return data;
    });

    return { savedTo: "Sheet1", emailsSent: 2 };
  },
});
```

> [accordion] What each part of the code does
>
> * **`zapier.runAction()`** runs an app action. `connection` names a connection alias, such as `sheets`, that you map to a real connection in the next step. `COL$A` to `COL$C` are the Google Sheets action's fields for columns A to C, and `worksheet: "0"` is the first sheet.
> * **`ctx.step({ ... })`** is the object form of a step. Put the function in `run`, next to retry settings such as `maxAttempts` and `retryDelaySeconds`.
> * **`ctx.wait()`** pauses the workflow for a number of seconds without holding a server open.
> * **The SDK client** sits at the top of the file. If you create it inside `run`, the workflow stops with a `DeterminismViolation` error.

> [accordion] Use a different app
>
> You can swap Gmail or Google Sheets for any app on Zapier. For each step you change, use the Zapier SDK CLI to find three values: the app, the action, and the action's input fields.
>
> 1. Find the app's key:
>
>    ```bash theme={null}
>    npx zapier-sdk list-apps --search "slack" --json | jq '.data[] | {slug, title}'
>    ```
>
> 2. List the app's actions. Use `key` as `action` and `action_type` as `actionType`:
>
>    ```bash theme={null}
>    npx zapier-sdk list-actions slack --json | jq '.data[] | {key, action_type, title}'
>    ```
>
> 3. List the action's input fields. Use each `key` in `inputs`:
>
>    ```bash theme={null}
>    npx zapier-sdk list-action-input-fields slack write ACTION_KEY --json | jq '.data[] | {key, title}'
>    ```
>
>    For the fields as JSON Schema, which coding agents read more reliably, run `get-action-input-fields-schema` with the same values.
>
> Then give the step a connection alias for the new app, and map it in step 2.
>
> If an app has no action for what you need, a step can call the app's API directly with `zapier.fetch()`, using your connection. Some Enterprise accounts block these calls. For details, check [Make custom API calls with fetch](https://docs.zapier.com/sdk/quickstart.md#step-9-make-custom-api-calls-with-fetch-optional).

## 2. Point the workflow at your apps

The workflow needs a Gmail connection, a Google Sheets connection, and the ID of your sheet. Use the Zapier SDK CLI to find your connections.

1. List your connections for each app and copy the `id` of the one to use:

   ```bash theme={null}
   npx zapier-sdk list-connections gmail --json | jq '.data[] | {id, title}'
   npx zapier-sdk list-connections google-sheets --json | jq '.data[] | {id, title}'
   ```

2. Create a file named `.zapierrc` that maps each alias in the code to a connection ID:

   ```json .zapierrc theme={null}
   {
     "connections": {
       "sheets": { "connectionId": "YOUR_SHEETS_CONNECTION_ID" },
       "gmail": { "connectionId": "YOUR_GMAIL_CONNECTION_ID" }
     }
   }
   ```

3. Copy your spreadsheet ID from the sheet's URL. It is the part between `/d/` and `/edit`. Replace `YOUR_SPREADSHEET_ID` in `workflow.ts` with it.

> [accordion] Connect an app for the first time
>
> If `list-connections` returns nothing for an app, you have no connection to it yet. [Connect the app](https://help.zapier.com/hc/en-us/articles/8496258785421) in Zapier, then run `list-connections` again.
>
> To start from your terminal instead, get a link to connect the app and open it in the browser where you are logged in to Zapier:
>
> ```bash theme={null}
> npx zapier-sdk get-connection-start-url gmail
> ```

## 3. Test it on your machine

Create a file named `test-onboarding.ts`. Use your own email address so the emails come to you:

```typescript test-onboarding.ts theme={null}
import onboardCustomer from "./workflow.js";

const response = await onboardCustomer({ name: "Alice", email: "you@example.com" });
console.log(JSON.stringify(response, null, 2));
```

Run it:

```bash theme={null}
npx tsx test-onboarding.ts
```

A new row appears in your sheet and the welcome email arrives. The output shows `done: false`, because the workflow paused at the wait.

After the 5-second wait ends, create `resume-onboarding.ts` with the `executionId` from the output, and run it:

```typescript resume-onboarding.ts theme={null}
import onboardCustomer from "./workflow.js";

const response = await onboardCustomer("EXECUTION_ID");
console.log(JSON.stringify(response, null, 2));
```

```bash theme={null}
npx tsx resume-onboarding.ts
```

The tips email arrives and the output shows `done: true` with the result.

> [accordion] Why the run pauses, and how resuming works
>
> On your machine, a paused workflow continues only when you call it again with its `executionId`. The first run returns:
>
> ```json Response theme={null}
> {
>   "done": false,
>   "executionId": "019487c9-1a20-7e64-b9c6-7a8b9c0d1e2f"
> }
> ```
>
> When you resume, the steps that already finished do not run again, so you get no second row and no second welcome email. On Zapier, waits end on their own, so you do not need to resume.

## 4. Deploy it with your connections

Create a Next Gen Zap for the workflow and save its ID:

```bash theme={null}
export ONBOARD_ID=$(npx zapier-sdk create-workflow "Onboard customer" \
  --description "Saves a new customer to Google Sheets and sends welcome emails." \
  --json | jq -r '.data.id')
```

Publish the workflow with your connections. `.zapierrc` works on your machine only, so pass the same connection IDs in `--connections`. Zapier installs `@zapier/zapier-sdk` and zod for you. In production, set exact versions so each publish installs the same code. To set them, check [Choose package versions](https://docs.zapier.com/sdk/build-a-zap-in-code.md#4-deploy-it-to-zapier):

```bash theme={null}
SOURCE_FILES=$(jq -n --rawfile w workflow.ts '{"workflow.ts": $w}')

npx zapier-sdk publish-workflow-version "$ONBOARD_ID" "$SOURCE_FILES" \
  --connections '{"sheets": {"connectionId": "YOUR_SHEETS_CONNECTION_ID"}, "gmail": {"connectionId": "YOUR_GMAIL_CONNECTION_ID"}}' \
  --manual \
  --json
```

The response lists both connections under `connections`.

> [!WARNING]
>
> Always pass `--connections` when the workflow uses apps. Without it, publishing succeeds, but every run fails at the first app step. If a connection ID is not in your account, publishing fails with a `connection-not-found` error that names the alias.

> [accordion] Add a trigger
>
> To run the Next Gen Zap when something happens in an app, such as a new form response, publish with `--trigger` instead of `--manual`. Use the Zapier SDK CLI to find each value:
>
> 1. List the app's triggers. Use `key` as `action` and `app_key` as `selectedApi`:
>
>    ```bash theme={null}
>    npx zapier-sdk list-triggers slack --json | jq '.data[] | {key, app_key, title}'
>    ```
>
> 2. List the trigger's input fields. Use each `key` in `params`:
>
>    ```bash theme={null}
>    npx zapier-sdk list-trigger-input-fields slack TRIGGER_KEY --json | jq '.data[] | {key, title, is_required}'
>    ```
>
> 3. Find the connection to use, the same way as in [step 2](#2-point-the-workflow-at-your-apps). Its `id` is the `authenticationId`.
>
> 4. Publish with the trigger, and leave out `--manual`:
>
>    ```bash theme={null}
>    npx zapier-sdk publish-workflow-version "$ONBOARD_ID" "$SOURCE_FILES" \
>      --connections '{"sheets": {"connectionId": "YOUR_SHEETS_CONNECTION_ID"}, "gmail": {"connectionId": "YOUR_GMAIL_CONNECTION_ID"}}' \
>      --trigger '{"selectedApi": "APP_KEY", "action": "TRIGGER_KEY", "authenticationId": "YOUR_CONNECTION_ID", "params": {"FIELD_KEY": "VALUE"}}' \
>      --json
>    ```
>
> You cannot pass both `--trigger` and `--manual`. A trigger that needs no connection, such as one in Schedule by Zapier, does not need `authenticationId`.
>
> The Next Gen Zap runs once for each new trigger record, such as each new form response, and `run` receives that record as `input`. `inputSchema` sets the type of `input` in your code, but Zapier does not check the record against it. Parse the record in `run` before you use its fields. You can still run the Next Gen Zap manually. For manual runs, Zapier uses `inputSchema` to find the input fields.

## 5. Run it on Zapier

Start the Next Gen Zap with your own email address:

```bash theme={null}
npx zapier-sdk run-workflow "$ONBOARD_ID" \
  --input '{"name": "Alice", "email": "you@example.com"}' \
  --json
```

A new row and both emails arrive, and the response shows `status: "finished"` with `output` set to `{ "savedTo": "Sheet1", "emailsSent": 2 }`.

You can also start the Next Gen Zap from the Workflow Manager. If it uses apps, the Workflow Manager asks you to confirm the app connections before the run starts.

If a step fails, Zapier retries it, so `status` can stay `started` for a few minutes before it changes to `failed`. Zapier also emails you, and the agent in the Workflow Manager explains the cause and suggests a fix.

> [accordion] Example of a failed run
>
> If the version has no connections, the `save-customer` step fails:
>
> ```json Response theme={null}
> {
>   "data": {
>     "status": "failed",
>     "output": null,
>     "error": {
>       "code": "execution_failed",
>       "message": "Step \"save-customer\" exhausted all retry attempts.",
>       "details": {
>         "name": "StepExhaustedError",
>         "cause": {
>           "code": "ZAPIER_CONFIGURATION_ERROR",
>           "message": "Connection \"sheets\" not found in connections map. Ensure the connection is defined in the manifest connections, or pass a connection ID directly."
>         }
>       }
>     }
>   }
> }
> ```
>
> `error.message` names the step. `error.details.cause.message` gives the reason. To fix this example, publish again with `--connections`. You cannot change a published version, so each fix publishes a new one.

## Next steps

> [card] [CLI reference](https://docs.zapier.com/sdk/cli-reference.md)
>
> Every option for `publish-workflow-version`, including `--trigger`.

> [card] [How Next Gen Zaps in code work](https://docs.zapier.com/sdk/define-durable.md)
>
> Learn how steps, waits, callbacks, and replays work.
