zapier-platform-cli 15.16.1 → 15.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README-source.md DELETED
@@ -1,2301 +0,0 @@
1
- <h1 align="center">
2
- <img alt="Zapier Logo" src="https://cdn.zappy.app/1cd66b15407db2d9a01fbe8d600772fe.svg" width="300px">
3
- <br>
4
- Platform CLI
5
- <br>
6
- <br>
7
- </h1>
8
-
9
- <p align="center">
10
- <a href="https://www.npmjs.com/package/zapier-platform-cli"><img src="https://img.shields.io/npm/v/zapier-platform-cli.svg" alt="npm version"></a>
11
- </p>
12
-
13
- Zapier is a platform for creating integrations and workflows. This CLI is your gateway to creating custom applications on the Zapier platform.
14
-
15
- You may find some documents on the Zapier site duplicate or outdated. The most up-to-date contents are always available on GitHub:
16
-
17
- - [Latest CLI Docs](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md)
18
- - [Latest CLI Reference](https://github.com/zapier/zapier-platform/blob/main/packages/cli/docs/cli.md)
19
- - [Latest Schema Docs](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md)
20
-
21
- Our code is updated frequently. To see a full list of changes, look no further than [the CHANGELOG](https://github.com/zapier/zapier-platform/blob/main/CHANGELOG.md).
22
-
23
- This doc describes the latest CLI version (**PACKAGE_VERSION**), as of this writing. If you're using an older version of the CLI, you may want to check out these historical releases:
24
-
25
- - CLI Docs: [14.x](https://github.com/zapier/zapier-platform/blob/zapier-platform-cli@14.1.2/packages/cli/README.md), [13.x](https://github.com/zapier/zapier-platform/blob/zapier-platform-cli@13.0.0/packages/cli/README.md)
26
- - CLI Reference: [14.x](https://github.com/zapier/zapier-platform/blob/zapier-platform-cli@14.1.2/packages/cli/docs/cli.md), [13.x](https://github.com/zapier/zapier-platform/blob/zapier-platform-cli@13.0.0/packages/cli/docs/cli.md)
27
- - Schema Docs: [14.x](https://github.com/zapier/zapier-platform/blob/zapier-platform-schema@14.1.2/packages/schema/docs/build/schema.md), [13.x](https://github.com/zapier/zapier-platform/blob/zapier-platform-schema@13.0.0/packages/schema/docs/build/schema.md)
28
-
29
- ## Table of Contents
30
-
31
- <!-- toc -->
32
- <!-- tocstop -->
33
-
34
-
35
- ## Getting Started
36
-
37
- > If you're new to Zapier Platform CLI, we strongly recommend you to walk through the [Tutorial](https://platform.zapier.com/quickstart/cli-tutorial) for a more thorough introduction.
38
-
39
- ### What is an App?
40
-
41
- > Note: this document uses "app" while modern Zapier nomenclature refers instead to "integrations". In both cases, the phrase refers to your code that connects your API with Zapier.
42
-
43
- A CLI App is an implementation of your app's API. You build a Node.js application
44
- that exports a single object ([JSON Schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#appschema)) and upload it to Zapier.
45
- Zapier introspects that definition to find out what your app is capable of and
46
- what options to present end users in the Zap Editor.
47
-
48
- For those not familiar with Zapier terminology, here is how concepts in the CLI map to the end user experience:
49
-
50
- * [Authentication](#authentication), (usually) which lets us know what credentials to ask users
51
- for. This is used during the "Connect Accounts" section of the Zap Editor.
52
- * [Triggers](#triggerssearchescreates), which read data *from* your API. These have their own section in the Zap Editor.
53
- * [Creates](#triggerssearchescreates), which send data *to* your API to create new records. These are listed under "Actions" in the Zap Editor.
54
- * [Searches](#triggerssearchescreates), which find specific records *in* your system. These are also listed under "Actions" in the Zap Editor.
55
- * [Resources](#resources), which define an object type in your API (say a contact) and the operations available to perform on it. These are automatically extracted into Triggers, Searches, and Creates.
56
-
57
- ### How does Zapier Platform CLI Work?
58
-
59
- Zapier takes the App you upload and sends it over to Amazon Web Service's Lambda. We then make calls to execute the operations your App defines as we execute Zaps. Your App takes the input data we provide (if any), makes the necessary HTTP calls, and returns the relevant data, which gets fed back into Zapier.
60
-
61
- ### Zapier Platform CLI vs UI
62
-
63
- The Zapier Platform includes two ways to build integrations: a CLI (to build integrations in your local development environment and deploy them from the command line), and a Visual Builder (to create integrations with a visual builder from your browser). Both use the same underlying platform, so pick the one that fits your team's needs best. The main difference is how you make changes to your code.
64
-
65
- Zapier Platform CLI is designed to be used by development teams who collaborate with version control and CI, and can be used to build more advanced integrations with custom coding for every part of your API calls and response parsing.
66
-
67
- [Zapier Platform UI](https://developer.zapier.com/) is designed to quickly spin up new integrations, and collaborate on them with teams that include non-developers. It's the quickest way to start using the Zapier platform—and you can manage your CLI apps' core details from its online UI as well. You can also [export](https://platform.zapier.com/docs/export) Zapier Platform UI integrations to CLI to start development in your browser, then finish out the core features in your local development environment.
68
-
69
- > Learn more in our [Zapier Platform UI vs CLI](https://platform.zapier.com/docs/vs) post.
70
-
71
- ### Requirements
72
-
73
- All Zapier CLI apps are run using Node.js `LAMBDA_VERSION`.
74
-
75
- You can develop using any version of Node you'd like, but your eventual code must be compatible with `LAMBDA_VERSION`. If you're using features not yet available in `LAMBDA_VERSION`, you can transpile your code to a compatible format with [Babel](https://babeljs.io/) (or similar).
76
-
77
- To ensure stability for our users, we strongly encourage you run tests on `LAMBDA_VERSION` sometime before your code reaches users. This can be done multiple ways.
78
-
79
- Firstly, by using a CI tool (like [Travis CI](https://travis-ci.org/) or [Circle CI](https://circleci.com/), which are free for open source projects). We provide a sample [.travis.yml](https://github.com/zapier/zapier-platform/blob/main/example-apps/trigger/.travis.yml) file in our template apps to get you started.
80
-
81
- Alternatively, you can change your local node version with tools such as [nvm](https://github.com/nvm-sh/nvm#installation-and-update). Then you can either swap to that version with `nvm use LAMBDA_VERSION`, or do `nvm exec LAMBDA_VERSION zapier test` so you can run tests without having to switch versions while developing.
82
-
83
-
84
- ### Quick Setup Guide
85
-
86
- First up is installing the CLI and setting up your auth to create a working "Zapier Example" application. It will be private to you and visible in your live [Zap Editor](https://zapier.com/app/editor).
87
-
88
- ```bash
89
- # install the CLI globally
90
- npm install -g zapier-platform-cli
91
-
92
- # setup auth to Zapier's platform with a deploy key
93
- zapier login
94
- ```
95
- > Note: If you log into Zapier via the single sign-on (Google, Facebook, or Microsoft), you may not have a Zapier password. If that's the case, you'll need to generate a deploy key, go to [your Zapier developer account here](https://developer.zapier.com/partner-settings/deploy-keys/) and create/copy a key, then run ```zapier login``` command with the --sso flag.
96
-
97
- Your Zapier CLI should be installed and ready to go at this point. Next up, we'll create our first app!
98
-
99
- ```bash
100
- # create a directory with the minimum required files
101
- zapier init example-app
102
-
103
- > Note: When you run `zapier init`, you'll be presented with a list of templates to start with. Pick the one that matches a feature you'll need (such as "dynamic-dropdown" for an integration with [dynamic dropdown fields](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#dynamic-dropdowns)), or select "minimal" for an integration with only the essentials. [View more example apps here](https://github.com/zapier/zapier-platform/tree/main/example-apps).
104
-
105
- # move into the new directory
106
- cd example-app
107
-
108
- # install all the libraries needed for your app
109
- npm install
110
- ```
111
- Depending on the authentication method for your app, you'll also likely need to set your `CLIENT_ID` and `CLIENT_SECRET` as environment variables. These are the consumer key and secret in OAuth1 terminology.
112
-
113
- ```bash
114
- # setting the environment variables on Zapier.com
115
- $ zapier env:set 1.0.0 CLIENT_ID=1234
116
- $ zapier env:set 1.0.0 CLIENT_SECRET=abcd
117
- ```
118
-
119
- You should now have a working local app. You can run several local commands to try it out.
120
-
121
- ```bash
122
- # run the local tests
123
- # the same as npm test, but adds some extra things to the environment
124
- zapier test
125
- ```
126
-
127
- Next, you'll probably want to upload app to Zapier itself so you can start testing live.
128
-
129
- ```bash
130
- # push your app to Zapier
131
- zapier push
132
- ```
133
-
134
- > Go check out our [full CLI reference documentation](https://github.com/zapier/zapier-platform/blob/main/packages/cli/docs/cli.md#zapier-cli-reference) to see all the other commands!
135
-
136
-
137
- ### Tutorial
138
-
139
- For a full tutorial, head over to our [Tutorial](https://platform.zapier.com/cli_tutorials/getting-started) for a comprehensive walkthrough for creating your first app. If this isn't your first rodeo, read on!
140
-
141
- ## Creating a Local App
142
-
143
- > Tip: Check the [Quick Setup](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#quick-setup-guide) if this is your first time using the platform!
144
-
145
- Creating an App can be done entirely locally and they are fairly simple Node.js apps using the standard Node environment and should be completely testable. However, a local app stays local until you `zapier register`.
146
-
147
- ```bash
148
- # make your folder
149
- mkdir zapier-example
150
- cd zapier-example
151
-
152
- # create the needed files from a template
153
- zapier init . --template minimal
154
-
155
- # install all the libraries needed for your app
156
- npm install
157
- ```
158
-
159
- If you'd like to manage your **local App**, use these commands:
160
-
161
- * `zapier init myapp` - initialize/start a local app project
162
- * `zapier convert 1234 .` - initialize/start from an existing app
163
- * `zapier scaffold resource Contact` - auto-injects a new resource, trigger, etc.
164
- * `zapier test` - run the same tests as `npm test`
165
- * `zapier validate` - ensure your app is valid
166
- * `zapier describe` - print some helpful information about your app
167
-
168
- ### Local Project Structure
169
-
170
- In your app's folder, you should see this general recommended structure. The `index.js` is Zapier's entry point to your app. Zapier expects you to export an `App` definition there.
171
-
172
- ```
173
- $ tree .
174
- .
175
- ├── README.md
176
- ├── index.js
177
- ├── package.json
178
- ├── triggers
179
- │   └── contact-by-tag.js
180
- ├── resources
181
- │   └── Contact.js
182
- ├── test
183
- │   ├── basic.js
184
- │   ├── triggers.js
185
- │   └── resources.js
186
- ├── build
187
- │   └── build.zip
188
- └── node_modules
189
- ├── ...
190
- └── ...
191
- ```
192
-
193
- ### Local App Definition
194
-
195
- The core definition of your `App` will look something like this, and is what your `index.js` should provide as the _only_ export:
196
-
197
- ```js
198
- [insert-file:./snippets/app-def.js]
199
- ```
200
-
201
- > Tip: You can use higher order functions to create any part of your App definition!
202
-
203
-
204
- ## Registering an App
205
-
206
- Registering your App with Zapier is a necessary first step which only enables basic administrative functions. It should happen before `zapier push` which is to used to actually expose an App Version in the Zapier interface and editor.
207
-
208
- ```bash
209
- # register your app
210
- zapier register "Zapier Example"
211
-
212
- # list your apps
213
- zapier integrations
214
- ```
215
-
216
- > Note: This doesn't put your app in the editor - see the docs on pushing an App Version to do that!
217
-
218
- If you'd like to manage your **App**, use these commands:
219
-
220
- * `zapier integrations` - list the apps in Zapier you can administer
221
- * `zapier register "App Title"` - creates a new app in Zapier
222
- * `zapier link` - lists and links a selected app in Zapier to your current folder
223
- * `zapier history` - print the history of your app
224
- * `zapier team:add user@example.com admin` - add an admin to help maintain/develop your app
225
- * `zapier users:add user@example.com 1.0.0` - invite a user try your app version 1.0.0
226
-
227
- ## Deploying an App Version
228
-
229
- An App Version is related to a specific App but is an "immutable" implementation of your app. This makes it easy to run multiple versions for multiple users concurrently. The App Version is pulled from the version within the `package.json`. To create a new App Version, update the version number in that file. By default, **every App Version is private** but you can `zapier promote` it to production for use by over 1 million Zapier users.
230
-
231
- ```bash
232
- # push your app version to Zapier
233
- zapier push
234
-
235
- # list your versions
236
- zapier versions
237
- ```
238
-
239
- If you'd like to manage your **Version**, use these commands:
240
-
241
- * `zapier versions` - list the versions for the current directory's app
242
- * `zapier push` - push the current version of current directory's app & version (read from `package.json`)
243
- * `zapier promote 1.0.0` - mark a version as the "production" version
244
- * `zapier migrate 1.0.0 1.0.1 [100%]` - move users between versions, regardless of deployment status
245
- * `zapier deprecate 1.0.0 2020-06-01` - mark a version as deprecated, but let users continue to use it (we'll email them)
246
- * `zapier env:set 1.0.0 KEY=VALUE` - set an environment variable to some value
247
- * `zapier delete:version 1.0.0` - delete a version entirely. This is mostly for clearing out old test apps you used personally. It will fail if there are any users. You probably want `deprecate` instead.
248
-
249
- > Note: To see the changes that were just pushed reflected in the browser, you have to manually refresh the browser each time you push.
250
-
251
-
252
- ### Private App Version (default)
253
-
254
- A simple `zapier push` will only create the App Version in your editor. No one else using Zapier can see it or use it.
255
-
256
-
257
- ### Sharing an App Version
258
-
259
- This is how you would share your app with friends, co-workers or clients. This is perfect for quality assurance, testing with active users or just sharing any app you like.
260
-
261
- ```bash
262
- # sends an email this user to let them view the app version 1.0.0 in the UI privately
263
- zapier users:add user@example.com 1.0.0
264
-
265
- # sends an email this user to let them admin the app (make changes just like you)
266
- zapier team:add user@example.com
267
- ```
268
-
269
- You can also invite anyone on the internet to your app by using the links from `zapier users:links`. The link should look something like `https://zapier.com/platform/public-invite/1/222dcd03aed943a8676dc80e2427a40d/`. You can put this in your help docs, post it to Twitter, add it to your email campaign, etc. You can choose an invite link specific to an app version or for the entire app (i.e. all app versions).
270
-
271
- ### Promoting an App Version
272
-
273
- Promotion is how you would share your app with every one of the 1 million+ Zapier users. If this is your first time promoting - you may have to wait for the Zapier team to review and approve your app.
274
-
275
- If this isn't the first time you've promoted your app - you might have users on older versions. You can `zapier migrate` to either move users over (which can be dangerous if you have breaking changes). Or, you can `zapier deprecate` to give users some time to move over themselves.
276
-
277
- ```bash
278
- # promote your app version to all Zapier users
279
- zapier promote 1.0.1
280
-
281
- # OPTIONAL - migrate your users between one app version to another
282
- zapier migrate 1.0.0 1.0.1
283
-
284
- # OR - mark the old version as deprecated
285
- zapier deprecate 1.0.0 2020-06-01
286
- ```
287
-
288
- ## Converting an Existing App
289
-
290
- If you have an existing Zapier [legacy Web Builder app](https://platform.zapier.com/conversion/maintaining), you can use it as a template to kickstart your local application.
291
-
292
- ```bash
293
- # Convert an existing Web Builder app to a CLI app in the my-app directory
294
- # App ID 1234 is from URL https://zapier.com/developer/builder/app/1234/development
295
- zapier convert 1234 my-app
296
- ```
297
-
298
- Your CLI app will be created and you can continue working on it.
299
-
300
- > Note: There is no way to convert a CLI app to a Web Builder app and we do not plan on implementing this.
301
-
302
- Introduced in v8.2.0, you are able to convert new integrations built in Zapier Platform UI to CLI.
303
-
304
- ```bash
305
- # the --version flag is what denotes this command is interacting with a Visual Builder app
306
- # zapier convert <APP_ID> --version <APP_VERSION> <PATH>
307
- zapier convert 1234 --version 1.0.1 my-app
308
- ```
309
-
310
- ## Authentication
311
-
312
- Most applications require some sort of authentication. The Zapier platform provides core behaviors for several common authentication methods that might be used with your application, as well as the ability to customize authentication further.
313
-
314
- When a user authenticates to your application through Zapier, a "connection" is created representing their authentication details. Data tied to a specific authentication connection is included in the [bundle object](#bundle-object) under `bundle.authData`.
315
-
316
- ### Basic
317
-
318
- Useful if your app requires two pieces of information to authenticate: `username` and `password`, which only the end user can provide. By default, Zapier will do the standard Basic authentication base64 header encoding for you (via an automatically registered middleware).
319
-
320
- > To create a new integration with basic authentication, run `zapier init [your app name] --template basic-auth`. You can also review an example of that code [here](https://github.com/zapier/zapier-platform/tree/main/example-apps/basic-auth).
321
-
322
- If your app uses Basic auth with an encoded API key rather than a username and password, like `Authorization: Basic APIKEYHERE:x`, consider the [Custom](#custom) authentication method instead.
323
-
324
- ```js
325
- [insert-file:./snippets/basic-auth.js]
326
- ```
327
-
328
- ### Digest
329
-
330
- *Added in v7.4.0.*
331
-
332
- The setup and user experience of Digest Auth is identical to Basic Auth. Users provide Zapier their username and password, and Zapier handles all the nonce and quality of protection details automatically.
333
-
334
- > To create a new integration with digest authentication, run `zapier init [your app name] --template digest-auth`. You can also review an example of that code [here](https://github.com/zapier/zapier-platform/tree/main/example-apps/digest-auth).
335
-
336
- > Limitation: Currently, MD5-sess and SHA are not implemented. Only the MD5 algorithm is supported. In addition, server nonces are not reused. That means for every `z.request` call, Zapier will send an additional request beforehand to get the server nonce.
337
-
338
- ```js
339
- [insert-file:./snippets/digest-auth.js]
340
- ```
341
-
342
- ### Custom
343
-
344
- Custom auth is most commonly used for apps that authenticate with API keys, although it also provides flexibility for any unusual authentication setup. You'll likely provide some custom `beforeRequest` middleware or a `requestTemplate` (see [Making HTTP Requests](#making-http-requests)) to pass in data returned from the authentication process, most commonly by adding/computing needed headers.
345
-
346
- > To create a new integration with custom authentication, run `zapier init [your app name] --template custom-auth`. You can also review an example of that code [here](https://github.com/zapier/zapier-platform/tree/main/example-apps/custom-auth).
347
-
348
- ```js
349
- [insert-file:./snippets/custom-auth.js]
350
- ```
351
-
352
- ### Session
353
-
354
- Session auth gives you the ability to exchange some user-provided data for some authentication data; for example, username and password for a session key. It can be used to implement almost any authentication method that uses that pattern - for example, alternative OAuth flows.
355
-
356
- > To create a new integration with session authentication, run `zapier init [your app name] --template session-auth`. You can also review an example of that code [here](https://github.com/zapier/zapier-platform/tree/main/example-apps/session-auth).
357
-
358
- ```js
359
- [insert-file:./snippets/session-auth.js]
360
- ```
361
-
362
- For Session auth, the function that fetches the additional authentication data needed to make API calls (`authentication.sessionConfig.perform`) has the user-provided fields in `bundle.inputData`. Afterwards, `bundle.authData` contains the data returned by that function (usually the session key or token).
363
-
364
- ### OAuth1
365
-
366
- *Added in `v7.5.0`.*
367
-
368
- Zapier's OAuth1 implementation matches [Twitter](https://developer.twitter.com/en/docs/tutorials/authenticating-with-twitter-api-for-enterprise/authentication-method-overview#oauth1.0a) and [Trello](https://developer.atlassian.com/cloud/trello/guides/rest-api/authorization/#using-basic-oauth) implementations of the 3-legged OAuth flow.
369
-
370
- > To create a new integration with OAuth1, run `zapier init [your app name] --template oauth1-trello`. You can also check out [oauth1-trello](https://github.com/zapier/zapier-platform/tree/main/example-apps/oauth1-trello), [oauth1-tumblr](https://github.com/zapier/zapier-platform/tree/main/example-apps/oauth1-tumblr), and [oauth1-twitter](https://github.com/zapier/zapier-platform/tree/main/example-apps/oauth1-twitter) for working example apps with OAuth1.
371
-
372
- The flow works like this:
373
-
374
- 1. Zapier makes a call to your API requesting a "request token" (also known as "temporary credentials").
375
- 2. Zapier sends the user to the authorization URL, defined by your app, along with the request token.
376
- 3. Once authorized, your website sends the user to the `redirect_uri` Zapier provided. Use `zapier describe` command to find out what it is: ![](https://zappy.zapier.com/117ECB35-5CCA-4C98-B74A-35F1AD9A3337.png)
377
- 4. Zapier makes a backend call to your API to exchange the request token for an "access token" (also known as "long-lived credentials").
378
- 5. Zapier stores the `access_token` and uses it to make calls on behalf of the user.
379
-
380
- You are required to define:
381
-
382
- * `getRequestToken`: The API call to fetch the request token
383
- * `authorizeUrl`: The authorization URL
384
- * `getAccessToken`: The API call to fetch the access token
385
-
386
- You'll also likely need to set your `CLIENT_ID` and `CLIENT_SECRET` as environment variables. These are the consumer key and secret in OAuth1 terminology.
387
-
388
- ```bash
389
- # setting the environment variables on Zapier.com
390
- $ zapier env:set 1.0.0 CLIENT_ID=1234
391
- $ zapier env:set 1.0.0 CLIENT_SECRET=abcd
392
-
393
- # and when running tests locally, don't forget to define them in .env or in the command!
394
- $ CLIENT_ID=1234 CLIENT_SECRET=abcd zapier test
395
- ```
396
-
397
- Your auth definition would look something like this:
398
-
399
- ```js
400
- [insert-file:./snippets/oauth1.js]
401
- ```
402
-
403
- For OAuth1, `authentication.oauth1Config.getRequestToken`, `authentication.oauth1Config.authorizeUrl`, and `authentication.oauth1Config.getAccessToken` have fields like `redirect_uri` and the temporary credentials in `bundle.inputData`. After `getAccessToken` runs, the resulting token value(s) will be stored in `bundle.authData` for the connection.
404
-
405
- Also, `authentication.oauth1Config.getAccessToken` has access to the additional return values in `rawRequest` and `cleanedRequest` should you need to extract other values (for example, from the query string).
406
-
407
- ### OAuth2
408
-
409
- Zapier's OAuth2 implementation is based on the `authorization_code` flow, similar to [GitHub](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps) and [Facebook](https://developers.facebook.com/docs/facebook-login/guides/advanced/manual-flow).
410
-
411
- > To create a new integration with OAuth2, run `zapier init [your app name] --template oauth2`. You can also check out [our working example app](https://github.com/zapier/zapier-platform/tree/main/example-apps/oauth2).
412
-
413
- If your app's OAuth2 flow uses a different grant type, such as `client_credentials`, try using [Session auth](#session) instead.
414
-
415
- The OAuth2 flow looks like this:
416
-
417
- 1. Zapier sends the user to the authorization URL defined by your app.
418
- 2. Once authorized, your website sends the user to the `redirect_uri` Zapier provided. Use the `zapier describe` command to find out what it is: ![](https://zappy.zapier.com/83E12494-0A03-4DB4-AA46-5A2AF6A9ECCC.png)
419
- 3. Zapier makes a backend call to your API to exchange the `code` for an `access_token`.
420
- 4. Zapier stores the `access_token` and uses it to make calls on behalf of the user.
421
- 5. (Optionally) Zapier can refresh the token if it expires.
422
-
423
- You are required to define:
424
-
425
- * `authorizeUrl`: The authorization URL
426
- * `getAccessToken`: The API call to fetch the access token
427
-
428
- If the access token has a limited life and you want to refresh the token when it expires, you'll also need to define the API call to perform that refresh (`refreshAccessToken`). You can choose to set `autoRefresh: true`, as in the example app, if you want Zapier to automatically make a call to refresh the token after receiving a 401. See [Stale Authentication Credentials](#stale-authentication-credentials) for more details on handling auth refresh.
429
-
430
- You'll also likely want to set your `CLIENT_ID` and `CLIENT_SECRET` as environment variables:
431
-
432
- ```bash
433
- # setting the environment variables on Zapier.com
434
- $ zapier env:set 1.0.0 CLIENT_ID=1234
435
- $ zapier env:set 1.0.0 CLIENT_SECRET=abcd
436
-
437
- # and when running tests locally, don't forget to define them in .env or in the command!
438
- $ CLIENT_ID=1234 CLIENT_SECRET=abcd zapier test
439
- ```
440
-
441
- Your auth definition would look something like this:
442
-
443
- ```js
444
- [insert-file:./snippets/oauth2.js]
445
- ```
446
-
447
- For OAuth2, `authentication.oauth2Config.authorizeUrl`, `authentication.oauth2Config.getAccessToken`, and `authentication.oauth2Config.refreshAccessToken` have fields like `redirect_uri` and `state` in `bundle.inputData`. After the code is exchanged for an access token and/or refresh token, those tokens are stored in `bundle.authData` for the connection.
448
-
449
- Also, `authentication.oauth2Config.getAccessToken` has access to the additional return values in `rawRequest` and `cleanedRequest` should you need to extract other values (for example, from the query string).
450
-
451
- If you define `fields` to collect additional details from the user, please note that `client_id` and `client_secret` are reserved keys and cannot be used as keys for input form fields.
452
-
453
- > Note: The OAuth2 `state` param is a [standard security feature](https://auth0.com/docs/secure/attack-protection/state-parameters) that helps ensure that authorization requests are only coming from your servers. Most OAuth clients have support for this and will send back the `state` query param that the user brings to your app. The Zapier Platform performs this check and this required field cannot be disabled. The state parameter is automatically generated by Zapier in the background, and can be accessed at `bundle.inputData.state`.
454
- Since Zapier uses the `state` to verify that GET requests to your redirect URL truly come from your app, it needs to be generated by Zapier so that it can be validated later (once the user confirms that they'd like to grant Zapier permission to access their account in your app).
455
-
456
-
457
- ### OAuth2 with PKCE
458
-
459
- *Added in v14.0.0.*
460
-
461
- Zapier's OAuth2 implementation also supports [PKCE](https://oauth.net/2/pkce/). This implementation is an extension of the OAuth2 `authorization_code` flow described above.
462
-
463
- To use PKCE in your OAuth2 flow, you'll need to set the following variables:
464
- 1. `enablePkce: true`
465
- 2. `getAccessToken.body` to include `code_verifier: "{{bundle.inputData.code_verifier}}"`
466
-
467
- The OAuth2 PKCE flow uses the same flow as OAuth2 but adds a few extra parameters:
468
-
469
- 1. Zapier computes a `code_verifier` and `code_challenge` internally and stores the `code_verifier` in the Zapier bundle.
470
- 2. Zapier sends the user to the authorization URL defined by your app. We automatically include the computed `code_challenge` and `code_challenge_method` in the authorization request.
471
- 3. Once authorized, your website sends the user to the `redirect_uri` Zapier provided.
472
- 4. Zapier makes a call to your API to exchange the code but you must include the computed `code_verifier` in the request for an `access_token`.
473
- 5. Zapier stores the `access_token` and uses it to make calls on behalf of the user.
474
-
475
- Your auth definition would look something like this:
476
-
477
- ```js
478
- [insert-file:./snippets/oauth2-pkce.js]
479
- ```
480
-
481
- The computed `code_verifier` uses this standard: [RFC 7636 Code Verifier](https://www.rfc-editor.org/rfc/rfc7636#section-4.1)
482
-
483
- The computed `code_challenge` uses this standard: [RFC 7636 Code Challenge](https://www.rfc-editor.org/rfc/rfc7636#section-4.2)
484
-
485
- ### Connection Label
486
-
487
- When a user connects to your app via Zapier and a connection is created to hold the related data in `bundle.authData`, the connection is automatically labeled with the app name. You also have the option of setting a connection label (`connectionLabel`), which can be extremely helpful to identify information like which user is connected or what instance of your app they are connected to. That way, users don't get confused if they have multiple connections to your app.
488
-
489
- When setting a connection label, you can use either a string with variable references (as shown in [Basic Auth](#basic)) or a function (as shown in [Digest Auth](#digest)).
490
-
491
- When using a string, you have access to the information in `bundle.authData` and the information returned from the test request in `bundle.inputData`, all at the top level. So in Basic auth, if `connectionLabel` is `{{username}}`, that refers to the username used for authentication.
492
-
493
- When using a function, this "hoisting" of data to the top level is skipped, and you must refer to data items by their fully qualified name, as shown in the line `return bundle.inputData.username;` in the Digest Auth snippet. `return username;` would not work in this context.
494
-
495
- **NOTE:** Do not use sensitive authentication data such as passwords or API keys in the connection label. It's visible in plain text on Zapier. The purpose of the label is to identify the connection for the user, so stick with data such as username or instance identifier that is meaningful but not sensitive.
496
-
497
- ### Domain and subdomain validation
498
-
499
- When adding a subdomain input field, commonly used in OAuth implementations, additional validation is strongly recommended to prevent a potential security vulnerability. If not taken into account, an attacker could utilize a maliciously constructed subdomain field (like `attacker-domain.com/`) in order to redirect OAuth connection requests to that attacker-controlled domain (because `attacker-domain.com/.your-domain.com` resolves to the attacker’s domain instead of the expected one).
500
-
501
- This vulnerability presents itself when:
502
-
503
- - The authentication method uses pre-configured tokens or secret values (for example, OAuth v2)
504
- - User is able to input a domain or subdomain when authenticating within Zapier
505
- - Integration stores sensitive authentication details (in environment variables, for example) which are used as part of the authentication process
506
-
507
- Taking the following steps prevents the potential for an attacker to access your integration’s sensitive authentication information, such as the OAuth client ID or secret.
508
-
509
- 1. If your integration allows for the user to provide a domain, validate the input against an allow-list of trusted domains.
510
-
511
- 2. If your integration allows for the user to provide a subdomain, add conditional validation for the subdomain string whenever you include the value in your OAuth HTTP requests. This change will prevent potential exploitation of the subdomain vulnerability.
512
-
513
- - If you’re using OAuth-based authentications, update the `getAccessToken` and optional `refreshAccessToken` configuration methods. If the integration uses [shorthand HTTP requests](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#shorthand-http-requests), switching to [manual HTTP requests](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#manual-http-requests) will allow you to perform this manual subdomain validation.
514
-
515
- Example code for handling subdomain validation:
516
-
517
- ```js
518
- const refreshAccessToken = async (z, bundle) => {
519
- // --- UPDATE: add your validation for the subdomain field before using it ---
520
- if (!/^[a-z0-9-]+$/.test(bundle.authData.yourSubdomainField)) {
521
- throw new Error(
522
- "Subdomain can only contain letters, numbers and dashes (-)."
523
- );
524
- }
525
-
526
-
527
- const response = await z.request({
528
- url: `https://${bundle.authData.yourSubdomainField}.mydomain.com/oauth/token`,
529
- method: "POST",
530
- body: {
531
- client_id: process.env.CLIENT_ID,
532
- client_secret: process.env.CLIENT_SECRET,
533
- grant_type: "refresh_token",
534
- refresh_token: bundle.authData.refresh_token,
535
- redirect_uri: bundle.inputData.redirect_uri,
536
- },
537
- });
538
-
539
-
540
- return {
541
- access_token: response.data.access_token,
542
- refresh_token: response.data.refresh_token,
543
- };
544
- };
545
- ```
546
-
547
- ## Resources
548
-
549
- A `resource` is a representation (as a JavaScript object) of one of the REST resources of your API. Say you have a `/recipes`
550
- endpoint for working with recipes; you can define a recipe resource in your app that will tell Zapier how to do create,
551
- read, and search operations on that resource.
552
-
553
- ```js
554
- [insert-file:./snippets/resources.js]
555
- ```
556
-
557
- The quickest way to create a resource is with the `zapier scaffold` command:
558
-
559
- ```bash
560
- zapier scaffold resource "Recipe"
561
- ```
562
-
563
- This will generate the resource file and add the necessary statements to the `index.js` file to import it.
564
-
565
-
566
- ### Resource Definition
567
-
568
- A resource has a few basic properties. The first is the `key`, which allows Zapier to identify the resource on our backend.
569
- The second is the `noun`, the user-friendly name of the resource that is presented to users throughout the Zapier UI.
570
-
571
- > Check out [this working example app](https://github.com/zapier/zapier-platform/tree/main/example-apps/resource) to see resources in action.
572
-
573
- After those, there is a set of optional properties that tell Zapier what methods can be performed on the resource.
574
- The complete list of available methods can be found in the [Resource Schema Docs](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#resourceschema).
575
- For now, let's focus on two:
576
-
577
- * `list` - Tells Zapier how to fetch a set of this resource. This becomes a Trigger in the Zapier Editor.
578
- * `create` - Tells Zapier how to create a new instance of the resource. This becomes an Action in the Zapier Editor.
579
-
580
- Here is a complete example of what the list method might look like
581
-
582
- ```js
583
- [insert-file:./snippets/recipe-list.js]
584
- ```
585
-
586
- The method is made up of two properties, a `display` and an `operation`. The `display` property ([schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#basicdisplayschema)) holds the info needed to present the method as an available Trigger in the Zapier Editor. The `operation` ([schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#resourceschema)) provides the implementation to make the API call.
587
-
588
- Adding a create method looks very similar.
589
-
590
- ```js
591
- [insert-file:./snippets/recipe-create.js]
592
- ```
593
-
594
- Every method you define on a `resource` Zapier converts to the appropriate Trigger, Create, or Search. Our examples
595
- above would result in an app with a New Recipe Trigger and an Add Recipe Create.
596
-
597
- Note the keys for the Trigger, Create, Search, and Search or Create are automatically generated (in case you want to use them in a dynamic dropdown), like: `{resourceName}List`, `{resourceName}Create`, `{resourceName}Search`, and `{resourceName}SearchOrCreate`; in the examples above, `{resourceName}` would be `recipe`.
598
-
599
-
600
- ## Triggers/Searches/Creates
601
-
602
- Triggers, Searches, and Creates are the way an app defines what it is able to do. Triggers read
603
- data into Zapier (i.e. watch for new recipes). Searches locate individual records (find recipe by title). Creates create
604
- new records in your system (add a recipe to the catalog).
605
-
606
- The definition for each of these follows the same structure. Here is an example of a trigger:
607
-
608
- ```js
609
- [insert-file:./snippets/trigger.js]
610
- ```
611
-
612
- You can find more details on the definition for each by looking at the [Trigger Schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#triggerschema),
613
- [Search Schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#searchschema), and [Create Schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#createschema).
614
-
615
- > To create a new integration with a premade trigger, search, or create, run `zapier init [your app name]` and select from the list that appears. You can also check out our working example apps [here](https://github.com/zapier/zapier-platform/tree/main/example-apps).
616
-
617
- > To add a trigger, search, or create to an existing integration, run `zapier scaffold [trigger|search|create] [noun]` to create the necessary files to your project. For example, `zapier scaffold trigger post` will create a new trigger called "New Post".
618
- ### Return Types
619
-
620
- Each of the 3 types of function should return a certain data type for use by the platform. There are automated checks to let you know when you're trying to pass the wrong type back. For reference, each expects:
621
-
622
- | Method | Return Type | Notes |
623
- |---------|-------------|----------------------------------------------------------------------------------------------------------------------|
624
- | Trigger | Array | 0 or more objects; passed to the [deduper](https://platform.zapier.com/docs/dedupe/) if polling |
625
- | Search | Array | 0 or more objects. Only the first object will be returned, so if len > 1, put the best match first |
626
- | Create | Object | Return values are evaluated by [`isPlainObject`](https://lodash.com/docs#isPlainObject) |
627
-
628
- When a trigger function returns an empty array, the Zap will not trigger. For REST Hook triggers, this can be used to filter data if the available subscription options are not specific enough for the Zap's needs.
629
-
630
- #### Returning Line Items (Array of Objects)
631
-
632
- In some cases, you may want to include multiple items in the data you return for Searches or Creates. To do that, return the set of items as an array of objects under a descriptive key. This may be as part of another object (like items in an invoice) or as multiple top-level items.
633
-
634
- For example, a Create Order action returning an order with multiple items might look like this:
635
-
636
- ```
637
- order = {
638
- name: 'Zap Zaplar',
639
- total_cost: 25.96,
640
- items: [
641
- { name: 'Zapier T-Shirt', unit_price: 11.99, quantity: 3, line_amount: 35.97, category: 'shirts' },
642
- { name: 'Orange Widget', unit_price: 7.99, quantity: 10, line_amount: 79.90, category: 'widgets' },
643
- { name:'Stuff', unit_price: 2.99, quantity: 7, line_amount: 20.93, category: 'stuff' },
644
- { name: 'Allbird Shoes', unit_price: 2.99, quantity: 7, line_amount: 20.93, category: 'shoes' },
645
- ],
646
- zip: 01002
647
- }
648
- ```
649
-
650
- While a Find Users search could return multiple items under an object key within an array, like this:
651
-
652
- ```
653
- result = [{
654
- users: [
655
- { name: 'Zap Zaplar', age: 12, city: 'Columbia', region: 'Missouri' },
656
- { name: 'Orange Crush', age: 28, city: 'West Ocean City', region: 'Maryland' },
657
- { name: 'Lego Brick', age: 91, city: 'Billund', region: 'Denmark' },
658
- ],
659
- }];
660
- ```
661
-
662
- A standard search would return just the inner array of users, and only the first user would be provided as a final result. Returning line items instead means that the "first result" return is the object containing all the user details within it.
663
-
664
- Using the standard approach is recommended, because not all Zapier integrations support line items directly, so users may need to take additional actions to reformat this data for use in their Zaps. More detail on that at [Use line items in Zaps](https://zapier.com/help/create/basics/use-line-items-in-zaps). However, there are use cases where returning multiple results is helpful enough to outweigh that additional effort.
665
-
666
- ### Fallback Sample
667
- In cases where Zapier needs to show an example record to the user, but we are unable to get a live example from the API, Zapier will fallback to this hard-coded sample. This should reflect the data structure of the Trigger's perform method, and have dummy values that we can show to any user.
668
-
669
- ```js
670
- ,sample: {
671
- dummydata_field1: 'This will be compared against your perform method output'
672
- style: 'mediterranean'
673
- }
674
- ```
675
-
676
- ## Input Fields
677
-
678
- On each trigger, search, or create in the `operation` directive, you can provide fields as an array of objects under `inputFields`. Input Fields are what your users see in Zapier when setting up your app's triggers and actions. For example, you might have a "Create Contact" action with fields like "First name", "Last name", "Email", etc. These fields will be able to accept input from the user, or from previous steps in a Zap. For example:
679
-
680
- ![gif of setting up an action field in Zap Editor](https://cdn.zappy.app/52721a3cb202446b7c298e303b710471.gif)
681
-
682
- You can find more details about setting action fields from a user perspective in [our help documentation](https://zapier.com/help/creating-zap/).
683
-
684
- Those fields have various options you can provide. Here is a brief example:
685
-
686
- ```js
687
- [insert-file:./snippets/fields.js]
688
- ```
689
-
690
- Notably, fields come in different types, which may look and act differently in the Zap editor. The default field display is a single-line input field.
691
-
692
- | Type | Behavior |
693
- |------|----------|
694
- | `string` | Accepts text input. |
695
- | `text` | Displays large, `<textarea>`-style entry box, accepts text input. |
696
- | `code` | Displays large, `<textarea>`-style box with a fixed-width font, accepts text input. |
697
- | `integer` | Accepts integer number values. |
698
- | `number` | Accepts any numeric value, including decimal numbers. |
699
- | `boolean` | Displays dropdown menu offering true and false options. Passes along `true` or `false`. |
700
- | `datetime` | Accepts both [precise and human-readable date-time values](https://help.zapier.com/hc/en-us/articles/8496259603341-Different-field-types-in-Zaps#date-time-fields-0-0). Passes along an ISO-formatted time string. |
701
- | `file` | Accepts a file object or a string. If a URL is provided in the string, Zapier will automatically make a GET for that file. Otherwise, a text file will be generated. |
702
- | `password` | Displays entered characters as hidden, accepts text input. Does not accept input from previous steps. |
703
- | `copy` | Does not allow users to enter data. Shows the value of the Markdown-formatted Help Text for the field as a rich text note in the Zap editor. Good for important notices to users. |
704
-
705
- You can find more details on the different field schema options at [our Field Schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#fieldschema).
706
-
707
- ### Custom/Dynamic Fields
708
-
709
- In some cases, you may need to provide dynamically-generated fields - especially for custom ones. This is common functionality for CRMs, form software, databases, and other highly-customizable platforms. Instead of an explicit field definition, you can provide a function we'll evaluate to return a list of fields - merging the dynamic with the static fields.
710
-
711
- > You should see `bundle.inputData` partially filled in as users provide data - even in field retrieval. This allows you to build hierarchical relationships into fields (e.g. only show issues from the previously selected project).
712
-
713
- > A function that returns a list of dynamic fields cannot include additional functions in that list to call for dynamic fields.
714
-
715
- ```js
716
- [insert-file:./snippets/custom-fields.js]
717
- ```
718
-
719
- Additionally, if there is a field that affects the generation of dynamic fields, you can set the property `altersDynamicFields: true`. This informs the Zapier UI whenever the value of that field changes, the input fields need to be recomputed. For example, imagine the selection on a static dropdown called "Dessert Type" determining whether the function generating dynamic fields includes the field "With Sprinkles?" or not. If the value in one input field affects others, this is an important property to set.
720
-
721
- ```js
722
- [insert-file:./snippets/alters-dynamic-fields.js]
723
- ```
724
-
725
- > Only dropdowns support `altersDynamicFields`.
726
-
727
- When using dynamic fields, the fields will be retrieved in three different contexts:
728
-
729
- * Whenever the value of a field with `altersDynamicFields` is changed, as described above.
730
- * Whenever the Zap Editor opens the "Set up" section for the trigger or action.
731
- * Whenever the "Refresh fields" button at the bottom of the Editor's "Set up" section is clicked.
732
-
733
- Be sure to set up your code accordingly - for example, don't rely on any input fields already having a value, since they won't have one the first time the "Set up" section loads.
734
-
735
- ### Dynamic Dropdowns
736
-
737
- Sometimes, API endpoints require clients to specify a parent object in order to create or access the child resources. For instance, specifying a spreadsheet id in order to retrieve its worksheets. Since people don't speak in auto-incremented ID's, it is necessary that Zapier offer a simple way to select that parent using human readable handles.
738
-
739
- Our solution is to present users a dropdown that is populated by making a live API call to fetch a list of parent objects. We call these special dropdowns "dynamic dropdowns."
740
-
741
- To define one you include the `dynamic` property on the `inputFields` object. The value for the property is a dot-separated _string_ concatenation.
742
-
743
- ```js
744
- [insert-file:./snippets/dynamic-dropdowns-one.js]
745
- ```
746
-
747
- The dot-separated string concatenation follows this pattern:
748
-
749
- - The key of the trigger you want to use to power the dropdown. _required_
750
- - The value to be made available in bundle.inputData. _required_
751
- - The human friendly value to be shown on the left of the dropdown in bold. _optional_
752
-
753
- In the above code example the dynamic property makes reference to a trigger with a key of project. Assuming the project trigger returns an array of objects and each object contains an id and name key, i.e.
754
-
755
- ```js
756
- [insert-file:./snippets/dynamic-dropdowns-two.js]
757
- ```
758
-
759
- The dynamic dropdown would look something like this.
760
- ![screenshot of dynamic dropdown in Zap Editor](https://cdn.zappy.app/6a90fcc532704f6c14b91586f5cd1d5b.png)
761
-
762
- In the first code example the dynamic dropdown is powered by a trigger. You can also use a resource to power a dynamic dropdown. To do this combine the resource key and the resource method using camel case.
763
-
764
- ```js
765
- [insert-file:./snippets/dynamic-dropdowns-three.js]
766
- ```
767
-
768
- In some cases you will need to power a dynamic dropdown but do not want to make the Trigger available to the end user. Here it is best practice to create the trigger and set `hidden: true` on it's display object.
769
-
770
- ```js
771
- [insert-file:./snippets/dynamic-dropdowns-four.js]
772
- ```
773
-
774
- You can have multiple dynamic dropdowns in a single Trigger or Action. And a dynamic dropdown can depend on the value chosen in another dynamic dropdown when making it's API call. Such as a Spreadsheet and Worksheet dynamic dropdown in a trigger or action. This means you must make sure that the key of the first dynamic dropdown is the same as referenced in the trigger powering the second.
775
-
776
- Let's say you have a Worksheet trigger with a `perform` method similar to this.
777
-
778
- ```js
779
- [insert-file:./snippets/dynamic-dropdowns-five.js]
780
- ```
781
-
782
- And your New Records trigger has a Spreadsheet and a Worksheet dynamic dropdown. The Spreadsheet dynamic dropdown must have a key of `spreadsheet_id`. When the user selects a spreadsheet via the dynamic dropdown the value chosen is made available in `bundle.inputData`. It will then be passed to the Worksheet trigger when the user clicks on the Worksheet dynamic dropdown.
783
-
784
- ```js
785
- [insert-file:./snippets/dynamic-dropdowns-six.js]
786
- ```
787
-
788
- The [Google Sheets](https://zapier.com/apps/google-sheets/integrations#triggers-and-actions) integration is an example of this pattern.
789
-
790
- If you want your trigger to perform specific scripting for a dynamic dropdown you will need to make use of `bundle.meta.isFillingDynamicDropdown`. This can be useful if need to make use of [pagination](#whats-the-deal-with-pagination-when-is-it-used-and-how-does-it-work) in the dynamic dropdown to load more options.
791
-
792
- ```js
793
- [insert-file:./snippets/dynamic-dropdowns-seven.js]
794
- ```
795
-
796
- ### Search-Powered Fields
797
-
798
- For fields that take id of another object to create a relationship between the two (EG: a project id for a ticket), you can specify the `search` property on the field to indicate that Zapier needs to prompt the user to setup a Search step to populate the value for this field. Similar to dynamic dropdowns, the value for this property is a dot-separated concatenation of a search's key and the field to use for the value.
799
-
800
- ```js
801
- [insert-file:./snippets/search-field.js]
802
- ```
803
-
804
- **NOTE:** This has to be combined with the `dynamic` property to give the user a guided experience when setting up a Zap.
805
-
806
- If you don't define a trigger for the `dynamic` property, the search connector won't show.
807
-
808
- ### Computed Fields
809
-
810
- In OAuth and Session Auth, Zapier automatically stores every value from an integration’s auth API response i.e. that’s `getAccessToken` and `refreshAccessToken` for OAuth and `getSessionKey` for session auth.
811
-
812
- You can return additional fields in these responses, on top of the expected `access_token` or `refresh_token` for OAuth and `sessionKey` for Session auth. They will be saved in `bundle.authData`. You can reference these fields in any subsequent API call as needed.
813
-
814
- > Note: Only OAuth and Session Auth support computed fields.
815
-
816
- If you want Zapier to validate that these additional fields exist, you need to use Computed Fields. If you define computed fields in your integration, Zapier will check to make sure those fields exist when it runs the authentication test API call.
817
-
818
- Computed fields work like any other field, though with `computed: true` property, and `required: false` as user can not enter computed fields themselves. Reference computed fields in API calls as `{{bundle.authData.field}}`, replacing `field` with that field's name from your test API call response.
819
-
820
- You can see examples of computed fields in the [OAuth2](#oauth2) or [Session Auth](#session) example sections.
821
-
822
- ### Nested & Children (Line Item) Fields
823
-
824
- When your action needs to accept an array of items, you can include an input field with the `children` attribute. The `children` attribute accepts a list of [fields](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#fieldschema) that can be input for each item in this array.
825
-
826
- ```js
827
- [insert-file:./snippets/input-fields-children.js]
828
- ```
829
-
830
- ## Output Fields
831
-
832
- On each trigger, search, or create in the operation directive - you can provide an array of objects as fields under the `outputFields`. Output Fields are what users see when they select a field provided by your trigger, search or create to map it to another.
833
-
834
- Output Fields are optional, but can be used to:
835
-
836
- - Define friendly labels for the returned fields. By default, we will *humanize* for example `my_key` as *My Key*.
837
- - Make sure that custom fields that may not be found in every live sample and - since they're custom to the connected account - cannot be defined in the static sample, can still be mapped.
838
- - (Added in v15.6.0) Define what field(s) can be used to uniquely identify and [deduplicate](#how-does-deduplication-work) items returned by a polling trigger call.
839
-
840
- The [schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#fieldschema) for `outputFields` is shared with `inputFields` but only these properties are relevant:
841
-
842
- - `key` - includes the field when not present in the live sample. When no `label` property is provided, `key` will be *humanized* and displayed as the field name.
843
- - `label` - defines the field name displayed to users.
844
- - `type` - defines the type for static sample data. A [validation warning](https://platform.zapier.com/docs/integration-checks-reference#d024---static-sample-respects-output-field-definition) will be displayed if the static sample does not match the specified type.
845
- - `required` - defines whether the field is required in static sample data. A [validation warning](https://platform.zapier.com/docs/integration-checks-reference#d024---static-sample-respects-output-field-definition) will be displayed if the value is true and the static sample does not contain the field.
846
- - `primary` - defines whether the field is part of the primary key for polling trigger [deduplication](#how-does-deduplication-work).
847
-
848
- Custom/Dynamic Output Fields are defined in the same way as [Custom/Dynamic Input Fields](#customdynamic-fields).
849
-
850
- ### Nested & Children (Line Item) Fields
851
-
852
- To define an Output Field for a nested field use `{{parent}}__{{key}}`. For children (line item) fields use `{{parent}}[]{{key}}`.
853
-
854
- ```js
855
- [insert-file:./snippets/output-fields.js]
856
- ```
857
-
858
- ## Buffered Create Actions
859
-
860
- _Added in v15.15.0. This feature is currently **internal-only**._
861
-
862
- A Buffered Create allows you to create objects in bulk with a single or fewer API request(s). This is useful when you want to reduce the number of requests made to your server. When enabled, Zapier holds the data until the buffer reaches a size limit or a certain time has passed, then sends the buffered data using the `performBuffer` function you define.
863
-
864
- To implement a Buffered Create, you define a [`buffer`](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#bufferconfigschema) configuration object and a `performBuffer` function in the `operation` object. In the `buffer` config object, you specify how you want to group the buffered data using the `groupedBy` setting and the maximum number of items to buffer using the `limit` setting.
865
-
866
- The `performBuffer` function should replace the `perform` function. Note that `perform` cannot be defined along with `performBuffer`. Check out the [`create` action operation schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#basiccreateactionoperationschema) for details.
867
-
868
- Similar to the general `perform` function accepting two arguments, [`z`](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#z-object) and [`bundle`](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#bundle-object) objects, the `performBuffer` function accepts [`z`](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#z-object) and [`bufferedBundle`](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#bufferedbundle-object) objects. They share the same `z` object, but the `bufferedBundle` object is different from the `bundle` object. The `bufferedBundle` object has an idempotency ID set at `bufferedBundle.buffer[].meta.id` for each object in the buffer. `performBuffer` would have to return the idempotency IDs to tell Zapier which objects were successfully written. Find the details about the `bufferedBundle` object [here](https://github.com/zapier/zapier-platform/blob/main/packages/cli/README.md#bufferedbundle-object).
869
-
870
- Here is an example of a Buffered Create action:
871
-
872
- ```js
873
- [insert-file:./snippets/buffered-create.js]
874
- ```
875
-
876
- ## Z Object
877
-
878
- We provide several methods off of the `z` object, which is provided as the first argument to all function calls in your app.
879
-
880
- > The `z` object is passed into your functions as the first argument - IE: `perform: (z) => {}`.
881
-
882
- ### `z.request([url], options)`
883
-
884
- `z.request([url], options)` is a promise based HTTP client with some Zapier-specific goodies. See [Making HTTP Requests](#making-http-requests). `z.request()` will [percent-encode](https://developer.mozilla.org/en-US/docs/Glossary/Percent-encoding) non-ascii characters and these reserved characters: ``:$/?#[]@$&+,;=^@`\``. Use [`skipEncodingChars`](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#requestschema) to modify this behaviour.
885
-
886
- ### `z.console`
887
-
888
- `z.console.log(message)` is a logging console, similar to Node.js `console` but logs remotely, as well as to stdout in tests. See [Log Statements](#console-logging)
889
-
890
- ### `z.dehydrate(func, inputData)`
891
-
892
- `z.dehydrate(func, inputData)` is used to lazily evaluate a function, perfect to avoid API calls during polling or for reuse. See [Dehydration](#dehydration).
893
-
894
- ### `z.dehydrateFile(func, inputData)`
895
-
896
- `z.dehydrateFile` is used to lazily download a file, perfect to avoid API calls during polling or for reuse. See [File Dehydration](#file-dehydration).
897
-
898
- ### `z.stashFile(bufferStringStream, [knownLength], [filename], [contentType])`
899
-
900
- `z.stashFile(bufferStringStream, [knownLength], [filename], [contentType])` is a promise based file stasher that returns a URL file pointer. See [Stashing Files](#stashing-files).
901
-
902
- ### `z.JSON`
903
-
904
- `z.JSON` is similar to the JSON built-in like `z.JSON.parse('...')`, but catches errors and produces nicer tracebacks.
905
-
906
- ### `z.hash()`
907
-
908
- `z.hash()` is a crypto tool for doing things like `z.hash('sha256', 'my password')`
909
-
910
- ### `z.errors`
911
-
912
- `z.errors` is a collection error classes that you can throw in your code, like `throw new z.errors.HaltedError('...')`.
913
-
914
- The available errors are:
915
-
916
- * `Error` (_added in v9.3.0_) - Stops the current operation, allowing for (auto) replay. Read more on [General Errors](#general-errors)
917
- * `HaltedError` - Stops current operation, but will never turn off Zap. Read more on [Halting Execution](#halting-execution)
918
- * `ExpiredAuthError` - Stops the current operation and emails user to manually reconnect. Read more on [Stale Authentication Credentials](#stale-authentication-credentials)
919
- * `RefreshAuthError` - (OAuth2 or Session Auth) Tells Zapier to refresh credentials and retry operation. Read more on [Stale Authentication Credentials](#stale-authentication-credentials)
920
- * `ThrottledError` (_new in v11.2.0_) - Tells Zapier to retry the current operation after a delay specified in seconds. Read more on [Handling Throttled Requests](#handling-throttled-requests)
921
-
922
- For more details on error handling in general, see [here](#error-handling).
923
-
924
- ### `z.cursor`
925
-
926
- The `z.cursor` object exposes two methods:
927
-
928
- * `z.cursor.get(): Promise<string|null>`
929
- * `z.cursor.set(string): Promise<null>`
930
-
931
- Any data you `set` will be available to that Zap for about an hour (or until it's overwritten). For more information, see: [paging](#paging).
932
-
933
- ### `z.generateCallbackUrl()`
934
-
935
- The `z.generateCallbackUrl()` will return a callback URL your app can `POST` to later for handling long running tasks (like transcription or encoding jobs). In the meantime, the Zap and Task will wait for your response and the user will see the Task marked as waiting.
936
-
937
- For example, in your `perform` you might do:
938
-
939
- ```js
940
- const perform = async (z, bundle) => {
941
- // something like this url:
942
- // https://zapier.com/hooks/callback/123/abcdef01-2345-6789-abcd-ef0123456789/abcdef0123456789abcdef0123456789abcdef01/
943
- // consider checking bundle.meta.isLoadingSample to determine if this is a test run or real run!
944
- const callbackUrl = z.generateCallbackUrl();
945
- await z.request({
946
- url: 'https://example.com/api/slow-job',
947
- method: 'POST',
948
- body: {
949
- // ... whatever your integration needs
950
- url: callbackUrl,
951
- },
952
- });
953
- return {"hello": "world"}; // available later in bundle.outputData
954
- };
955
- ```
956
-
957
- And in your own `/api/slow-job` view (or more likely, an async job) you'd make this request to Zapier when the long-running job completes to populate `bundle.cleanedRequest`:
958
-
959
- ```http
960
- POST /hooks/callback/123/abcdef01-2345-6789-abcd-ef0123456789/abcdef0123456789abcdef0123456789abcdef01/ HTTP/1.1
961
- Host: zapier.com
962
- Content-Type: application/json
963
-
964
- {"foo":"bar"}
965
- ```
966
- > We recommend using `bundle.meta.isLoadingSample` to determine if the execution is happening in the foreground (IE: during Zap setup) as using `z.generateCallbackUrl()` can be inappropriate given the disconnect. Instead, wait for the long running request without generating a callback, or if you must, return stubbed data.
967
-
968
- By default the payload `POST`ed to the callback URL will augment the data returned from the initial `perform` to compose the final value.
969
-
970
- If you need to customize what the final value should be you can define a `performResume` method that receives three bundle properties:
971
-
972
- * `bundle.outputData` is `{"hello": "world"}`, the data returned from the initial `perform`
973
- * `bundle.cleanedRequest` is `{"foo": "bar"}`, the payload from the callback URL
974
- * `bundle.rawRequest` is the full request object corresponding to `bundle.cleanedRequest`
975
-
976
- ```js
977
- const performResume = async (z, bundle) => {
978
- // this will give a final value of: {"hello": "world", "foo": "bar"}
979
- // which is the default behavior when a custom `performResume` is not
980
- // defined.
981
- return { ...bundle.outputData, ...bundle.cleanedRequest };
982
- };
983
- ```
984
-
985
- > The app will have a maximum of 30 days to `POST` to the callback URL. If a user deletes or modifies the Zap or Task in the meantime, we will not resume the task.
986
-
987
- > `performResume` will only run when the Zap runs live, and cannot be tested in the Zap Editor when configuring the Zap. It is possible to use `bundle.meta.isLoadingSample` to load a fixed sample to allow users to test a step that includes `performResume`.
988
-
989
-
990
- ## Bundle Object
991
-
992
- This object holds the user's auth details and the data for the API requests.
993
-
994
- > The `bundle` object is passed into your functions as the second argument - IE: `perform: (z, bundle) => {}`.
995
-
996
- ### `bundle.authData`
997
-
998
- `bundle.authData` is user-provided authentication data, like `api_key` or `access_token`. [Read more on authentication.](#authentication)
999
-
1000
- ### `bundle.inputData`
1001
-
1002
- `bundle.inputData` is user-provided data for this particular run of the trigger/search/create, as defined by the [`inputFields`](#input-fields). For example:
1003
-
1004
- ```js
1005
- {
1006
- createdBy: 'his name is Bobby Flay',
1007
- style: 'he cooks mediterranean',
1008
- scheduledAt: "2021-09-09T09:00:00-07:00"
1009
- }
1010
- ```
1011
-
1012
- ### `bundle.inputDataRaw`
1013
-
1014
- `bundle.inputDataRaw` is like `bundle.inputData`, but before processing such as interpreting friendly datetimes and rendering `{{curlies}}`:
1015
-
1016
- ```js
1017
- {
1018
- createdBy: 'his name is {{123__chef_name}}',
1019
- style: 'he cooks {{456__style}}',
1020
- scheduledAt: "today"
1021
- }
1022
- ```
1023
-
1024
- > "curlies" represent data mapped in from previous steps. They take the form `{{NODE_ID__key_name}}`.
1025
-
1026
- You'll usually want to use `bundle.inputData` instead.
1027
-
1028
- ### `bundle.meta`
1029
-
1030
- `bundle.meta` contains extra information useful for doing advanced behaviors depending on what the user is doing. It has the following options:
1031
-
1032
- | key | default | description |
1033
- | --- | --- | --- |
1034
- | `isLoadingSample` | `false` | If true, this run was initiated manually via the Zap Editor |
1035
- | `isFillingDynamicDropdown` | `false` | If true, this poll is being used to populate a dynamic dropdown. You only need to return the fields you specified (such as `id` and `name`), though returning everything is fine too |
1036
- | `isPopulatingDedupe` | `false` | If true, the results of this poll will be used to initialize the deduplication list rather than trigger a zap. You should grab as many items as possible. See also: [deduplication](#dedup) |
1037
- | `limit` | `-1` | The number of items you should fetch. `-1` indicates there's no limit. Build this into your calls insofar as you are able |
1038
- | `page` | `0` | Used in [paging](#paging) to uniquely identify which page of results should be returned |
1039
- | `isTestingAuth` | `false` | (legacy property) If true, the poll was triggered by a user testing their account (via [clicking "test"](https://cdn.zapier.com/storage/photos/5c94c304ce11b02c073a973466a7b846.png) or during setup). We use this data to populate the auth label, but it's mostly used to verify we made a successful authenticated request |
1040
- | `withSearch` | `undefined` | When a create is called as part of a search-or-create step, `withSearch` will be the key of the search. |
1041
-
1042
- > Before v8.0.0, the information in `bundle.meta` was different. See [the old docs](https://github.com/zapier/zapier-platform-cli/blob/a058e6d538a75d215d2e0c52b9f49a97218640c4/README.md#bundlemeta) for the previous values and [the wiki](https://github.com/zapier/zapier-platform/wiki/bundle.meta-changes) for a mapping of old values to new.
1043
-
1044
- Here's an example of a polling trigger that is also used to power a dynamic dropdown:
1045
-
1046
- ```js
1047
- const perform = async (z, bundle) => {
1048
- const params = { per_page: 100 }; // poll for the most recent 100 teams
1049
-
1050
- if (bundle.meta.isFillingDynamicDropdown) {
1051
- // dynamic dropdowns support pagination
1052
- params.per_page = 30;
1053
- params.offset = params.per_page * bundle.meta.page;
1054
- }
1055
-
1056
- const response = await z.request({
1057
- url: `${API_BASE_URL}/teams`,
1058
- params,
1059
- });
1060
-
1061
- return response.json;
1062
- };
1063
- // ...
1064
- ```
1065
-
1066
-
1067
-
1068
- ### `bundle.rawRequest`
1069
-
1070
- > `bundle.rawRequest` is only available in the `perform` for webhooks, `getAccessToken` for OAuth authentication methods, and `performResume` in a callback action.
1071
-
1072
- `bundle.rawRequest` holds raw information about the HTTP request that triggered the `perform` method or that represents the user's browser request that triggered the `getAccessToken` call:
1073
-
1074
- ```
1075
- {
1076
- method: 'POST',
1077
- querystring: 'foo=bar&baz=qux',
1078
- headers: {
1079
- 'Content-Type': 'application/json'
1080
- },
1081
- content: '{"hello": "world"}'
1082
- }
1083
- ```
1084
-
1085
- In `bundle.rawRequest`, headers other than `Content-Length` and `Content-Type` will be prefixed with `Http-`, and all headers will be named in Camel-Case. For example, the header `X-Time-GMT` would become `Http-X-Time-Gmt`.
1086
-
1087
- ### `bundle.cleanedRequest`
1088
-
1089
- > `bundle.cleanedRequest` is only available in the `perform` for webhooks, `getAccessToken` for OAuth authentication methods, and `performResume` in a callback action.
1090
-
1091
- `bundle.cleanedRequest` will return a formatted and parsed version of the request. Some or all of the following will be available:
1092
-
1093
- ```
1094
- {
1095
- method: 'POST',
1096
- querystring: {
1097
- foo: 'bar',
1098
- baz: 'qux'
1099
- },
1100
- headers: {
1101
- 'Content-Type': 'application/json'
1102
- },
1103
- content: {
1104
- hello: 'world'
1105
- }
1106
- }
1107
- ```
1108
-
1109
- ### `bundle.outputData`
1110
-
1111
- > `bundle.outputData` is only available in the `performResume` in a callback action.
1112
-
1113
- `bundle.outputData` will return a whatever data you originally returned in the `perform`, allowing you to mix that with `bundle.rawRequest` or `bundle.cleanedRequest`.
1114
-
1115
-
1116
- ### `bundle.targetUrl`
1117
-
1118
- > `bundle.targetUrl` is only available in the `performSubscribe` and `performUnsubscribe` methods for webhooks.
1119
-
1120
- This the URL to which you should send hook data. It'll look something like `https://hooks.zapier.com/1234/abcd`. We provide it so you can make a POST request to your server. Your server should store this URL and use is as a destination when there's new data to report.
1121
-
1122
- For example:
1123
-
1124
- ```js
1125
- const subscribeHook = async (z, bundle) => {
1126
-
1127
- const options = {
1128
- url: 'https://57b20fb546b57d1100a3c405.mockapi.io/api/hooks',
1129
- method: 'POST',
1130
- body: {
1131
- url: bundle.targetUrl, // bundle.targetUrl has the Hook URL this app should call
1132
- },
1133
- };
1134
-
1135
- const response = await z.request(options);
1136
- return response.data; // or response.json if you're using core v9 or older
1137
- };
1138
-
1139
- module.exports = {
1140
- // ...
1141
- performSubscribe: subscribeHook,
1142
- // ...
1143
- };
1144
- ```
1145
-
1146
- Read more in the [REST hook example](https://github.com/zapier/zapier-platform/blob/main/example-apps/rest-hooks/triggers/recipe.js).
1147
-
1148
- ### `bundle.subscribeData`
1149
-
1150
- > `bundle.subscribeData` is available in the `perform` and `performUnsubscribe` method for webhooks.
1151
-
1152
- This is an object that contains the data you returned from the `performSubscribe` function. It should contain whatever information you need send a `DELETE` request to your server to stop sending webhooks to Zapier.
1153
-
1154
- Read more in the [REST hook example](https://github.com/zapier/zapier-platform/blob/main/example-apps/rest-hooks/triggers/recipe.js).
1155
-
1156
- ## BufferedBundle Object
1157
-
1158
- *Added in v15.15.0.*
1159
-
1160
- This object holds a user's auth details (`bufferedBundle.authData`) and the buffered data (`bufferedBundle.buffer`) for the API requests. It is used only with a `create` action's `performBuffer` function.
1161
-
1162
- > The `bufferedBundle` object is passed into the `performBuffer` function as the second argument - IE: `performBuffer: async (z, bufferedBundle) => {}`.
1163
-
1164
- ### `bufferedBundle.authData`
1165
-
1166
- It is a user-provided authentication data, like `api_key` or `access_token`. [Read more on authentication.](#authentication)
1167
-
1168
- ### `bufferedBundle.groupedBy`
1169
-
1170
- It is a user-provided data for a set of selected [`inputFields`](#input-fields) to group the multiple runs of a `create` action by.
1171
-
1172
- ### `bufferedBundle.buffer`
1173
-
1174
- It is an array of objects of user-provided data and some meta data to allow multiple runs of a `create` action be processed in a single API request.
1175
-
1176
- #### `bufferedBundle.buffer[].inputData`
1177
-
1178
- It is a user-provided data for a particular run of a `create` action in the buffer, as defined by the [`inputFields`](#input-fields).
1179
-
1180
- #### `bufferedBundle.buffer[].meta`
1181
-
1182
- It contains an idempotency `id` provided to the `create` action to identify each run's data in the buffered data.
1183
-
1184
- ## Environment
1185
-
1186
- Apps can define environment variables that are available when the app's code executes. They work just like environment
1187
- variables defined on the command line. They are useful when you have data like an OAuth client ID and secret that you
1188
- don't want to commit to source control. Environment variables can also be used as a quick way to toggle between
1189
- a staging and production environment during app development.
1190
-
1191
- It is important to note that **variables are defined on a per-version basis!** When you push a new version, the
1192
- existing variables from the previous version are copied, so you don't have to manually add them. However, edits
1193
- made to one version's environment will not affect the other versions.
1194
-
1195
- ### Defining Environment Variables
1196
-
1197
- To define an environment variable, use the `env` command:
1198
-
1199
- ```bash
1200
- # Will set the environment variable on Zapier.com
1201
- zapier env:set 1.0.0 MY_SECRET_VALUE=1234
1202
- ```
1203
-
1204
- You will likely also want to set the value locally for testing.
1205
-
1206
- ```bash
1207
- export MY_SECRET_VALUE=1234
1208
- ```
1209
-
1210
- Alternatively, we provide some extra tooling to work with an `.env` (or `.environment`, see below note) that looks like this:
1211
-
1212
- ```
1213
- MY_SECRET_VALUE=1234
1214
- ```
1215
-
1216
- > `.env` is the new recommended name for the environment file since v5.1.0. The old name `.environment` is deprecated but will continue to work for backward compatibility.
1217
-
1218
- And then in your `test/basic.js` file:
1219
-
1220
- ```js
1221
- const zapier = require('zapier-platform-core');
1222
-
1223
- should('some tests', () => {
1224
- zapier.tools.env.inject(); // testing only!
1225
- console.log(process.env.MY_SECRET_VALUE);
1226
- // should print '1234'
1227
- });
1228
- ```
1229
-
1230
- > This is a popular way to provide `process.env.ACCESS_TOKEN || bundle.authData.access_token` for convenient testing.
1231
-
1232
- > **NOTE** Variables defined via `zapier env:set` will _always_ be uppercased. For example, you would access the variable defined by `zapier env:set 1.0.0 foo_bar=1234` with `process.env.FOO_BAR`.
1233
-
1234
-
1235
- ### Accessing Environment Variables
1236
-
1237
- To view existing environment variables, use the `env` command.
1238
-
1239
- ```bash
1240
- # Will print a table listing the variables for this version
1241
- zapier env:get 1.0.0
1242
- ```
1243
-
1244
- Within your app, you can access the environment via the standard `process.env` - any values set via local `export` or `zapier env:set` will be there.
1245
-
1246
- For example, you can access the `process.env` in your perform functions and in templates:
1247
-
1248
- ```js
1249
- [insert-file:./snippets/process-env.js]
1250
- ```
1251
-
1252
- > Note! Be sure to lazily access your environment variables - see [When to use placeholders or curlies?](#when-to-use-placeholders-or-curlies).
1253
-
1254
-
1255
- ## Adding Throttle Configuration
1256
-
1257
- *Added in v15.4.0.*
1258
-
1259
- When a throttle configuration is set for an action, Zapier uses it to apply throttling when the limit for the timeframe window is exceeded. It can be set at the root level and/or on an action. When set at the root level, it is the default throttle configuration used on each action of the integration. And when set in an action's operation object, the root-level default is overwritten for that action only. Note that the throttle limit is not shared across actions unless for those with the same key, window, limit, and scope when "action" is not in the scope.
1260
-
1261
- To throttle an action, you need to set a `throttle` object with the following variables:
1262
- 1. `window [integer]`: The timeframe, in seconds, within which the system tracks the number of invocations for an action. The number of invocations begins at zero at the start of each window.
1263
- 2. `limit [integer]`: The maximum number of invocations for an action, allowed within the timeframe window.
1264
- 3. `key [string]` (_added in v15.6.0_): The key to throttle with in combination with the scope. User data provided for the input fields can be used in the key with the use of the curly braces referencing. For example, to access the user data provided for the input field "test_field", use `{{bundle.inputData.test_field}}`. Note that a required input field should be referenced to get user data always.
1265
- 4. `retry [boolean]` (_added in v15.8.0_): The effect of throttling on the tasks of the action. `true` means throttled tasks are automatically retried after some delay, while `false` means tasks are held without retry. It defaults to `true`. NOTE that it has no effect on polling triggers and should not be set.
1266
- 5. `filter [string]` (_added in v15.8.0_): EXPERIMENTAL: Account-based attribute to override the throttle by. You can set to one of the following: "free", "trial", "paid". Therefore, the throttle scope would be automatically set to "account" and ONLY the accounts based on the specified filter will have their requests throttled based on the throttle overrides while the rest are throttled based on the original configuration.
1267
- 6. `scope [array]`: The granularity to throttle by. You can set the scope to one or more of the following options;
1268
- - 'user' - Throttles based on user ids.
1269
- - 'auth' - Throttles based on auth ids.
1270
- - 'account' - Throttles based on account ids for all users under a single account.
1271
- - 'action' - Throttles the action it is set on separately from other actions.
1272
- 7. `overrides [array[object]]` (_added in v15.6.0_): EXPERIMENTAL: Overrides the original throttle configuration based on a Zapier account attribute;
1273
- - `window [integer]`: Same description as above.
1274
- - `limit [integer]`: Same description as above.
1275
- - `filter [string]`: Account-based attribute to override the throttle by. You can set to one of the following: "free", "trial", "paid". Therefore, the throttle scope would be automatically set to "account" and ONLY the accounts based on the specified filter will have their requests throttled based on the throttle overrides while the rest are throttled based on the original configuration.
1276
- - `retry [boolean]` (_added in v15.6.1_): The effect of throttling on the tasks of the action. `true` means throttled tasks are automatically retried after some delay, while `false` means tasks are held without retry. It defaults to `true`. NOTE that it has no effect on polling triggers and should not be set.
1277
-
1278
- Both `window` and `limit` are required and others are optional. By default, throttling is scoped to the action and account.
1279
-
1280
- Here is a typical usage of the throttle configuration:
1281
-
1282
- ```js
1283
- [insert-file:./snippets/throttle-configuration.js]
1284
- ```
1285
-
1286
-
1287
- ## Making HTTP Requests
1288
-
1289
- There are two ways to make HTTP requests:
1290
-
1291
- 1. [**Shorthand HTTP Requests**](#shorthand-http-requests) - Easy to use, but limits what you can control. Best for simple requests.
1292
- 2. [**Manual HTTP Requests**](#manual-http-requests) - Gives you full control over the request and response.
1293
-
1294
- Use these helper constructs to reduce boilerplate:
1295
-
1296
- 1. `requestTemplate` - an object literal of [HTTP request options](#http-request-options) that will be merged with every request.
1297
- 2. `beforeRequest` - [middleware](#using-http-middleware) that mutates every request before it is sent.
1298
- 3. `afterResponse` - [middleware](#using-http-middleware) that mutates every response before it is completed.
1299
-
1300
- > Note: you can install any HTTP client you like - but this is greatly discouraged as you lose [automatic HTTP logging](#http-logging) and middleware.
1301
-
1302
- ### Shorthand HTTP Requests
1303
-
1304
- For simple HTTP requests that do not require special pre- or post-processing, you can specify the [HTTP request options](#http-request-options) as an object literal in your app definition.
1305
-
1306
- This features:
1307
-
1308
- 1. Lazy `{{curly}}` replacement.
1309
- 2. JSON and form body de-serialization.
1310
- 3. Automatic non-2xx error raising.
1311
-
1312
- ```js
1313
- [insert-file:./snippets/shorthand-request.js]
1314
- ```
1315
-
1316
- In the URL above, `{{bundle.authData.subdomain}}` is automatically replaced with the live value from the bundle. If the call returns a non 2xx return code, an error is automatically raised. The response body is automatically parsed as JSON or form-encoded and returned.
1317
-
1318
- An error will be raised if the response cannot be parsed as JSON or form-encoded. To use shorthand requests with other response types, add [middleware](#using-http-middleware) that sets `response.data` to the parsed response.
1319
-
1320
- ### Manual HTTP Requests
1321
-
1322
- Use this when you need full control over the request/response. For example:
1323
-
1324
- 1. To do processing (usually involving [`bundle.inputData`](#bundleinputdata)) before a request is made
1325
- 2. To do processing of an API's response before you return data to Zapier
1326
- 3. To process an unusual response type, such as XML
1327
-
1328
- To make a manual request, pass your [request options](#http-request-options) to `z.request()` then use the resulting [response object](#http-response-object) to return the data you want:
1329
-
1330
- ```js
1331
- [insert-file:./snippets/manual-request.js]
1332
- ```
1333
-
1334
- Manual requests perform lazy `{{curly}}` replacement. In the URL above, `{{bundle.authData.subdomain}}` is automatically replaced with the live value from the bundle.
1335
-
1336
- #### POST and PUT Requests
1337
-
1338
- To POST or PUT data to your API you can do this:
1339
-
1340
- ```js
1341
- [insert-file:./snippets/put.js]
1342
- ```
1343
-
1344
- > Note: you need to call `z.JSON.stringify()` before setting the `body`.
1345
-
1346
- ### Using HTTP middleware
1347
-
1348
- To process all HTTP requests in a certain way, use the `beforeRequest` and `afterResponse` middleware functions.
1349
-
1350
- Middleware functions go in your app definition:
1351
-
1352
- ```js
1353
- [insert-file:./snippets/middleware.js]
1354
- ```
1355
-
1356
- A `beforeRequest` middleware function takes a request options object, and returns a (possibly mutated) request object. An `afterResponse` middleware function takes a response object, and returns a (possibly mutated) response object. Middleware functions are executed in the order specified in the app definition, and each subsequent middleware receives the request or response object returned by the previous middleware.
1357
-
1358
- Middleware functions can be asynchronous - just return a promise from the middleware function.
1359
-
1360
- The second argument for middleware is the `z` object, but it does *not* include `z.request()` as using that would easily create infinite loops.
1361
-
1362
- Here is the full request lifecycle when you call `z.request({...})`:
1363
-
1364
- 1. set defaults on the `request` object
1365
- 2. run your `beforeRequest` middleware functions in order
1366
- 3. add applicable auth headers (e.g. adding `Basic ...` for `basic` auth), if applicable
1367
- 4. add `request.params` to `request.url`
1368
- 5. execute the `request`, store the result in `response`
1369
- 6. try to auto-parse response body for non-raw requests, store result in `response.data`
1370
- 7. log the request to Zapier's logging server
1371
- 8. if the status code is `401`, you're using a refresh-able auth (such as `oauth2` or `session`) _and_ `autoRefresh` is `true` in your auth configuration, throw a `RefreshAuthError`. The server will attempt to refresh the authentication again and retry the whole step
1372
- 9. run your `afterResponse` middleware functions in order
1373
- 10. call `response.throwForStatus()` unless `response.skipThrowForStatus` is `true`
1374
-
1375
- The resulting response object is returned from `z.request()`.
1376
-
1377
- > Example App: check out https://github.com/zapier/zapier-platform/tree/main/example-apps/middleware for a working example app using HTTP middleware.
1378
-
1379
- #### Error Response Handling
1380
-
1381
- Since `v10.0.0`, `z.request()` calls `response.throwForStatus()` before it returns a response. You can disable automatic error throwing by setting `skipThrowForStatus` on the request object:
1382
-
1383
- ```js
1384
- // Disable automatic error throwing on the request object
1385
- const perform = async (z, bundle) => {
1386
- const response = await z.request({
1387
- url: '...',
1388
- skipThrowForStatus: true
1389
- });
1390
- // Now you handle error response on your own.
1391
- // The following is equivalent to response.throwForStatus(),
1392
- // but you have to remember to do it on every request
1393
- if (response.status >= 400) {
1394
- throw new z.errors.ResponseError(response);
1395
- }
1396
- };
1397
- ```
1398
-
1399
- You can also do it in `afterResponse` if the API uses a status code >= 400 that should not be treated as an error.
1400
-
1401
- ```js
1402
- // Don't throw an error when response status is 456
1403
- const disableAutoThrowOn456 = (response, z) => {
1404
- if (response.status === 456) {
1405
- response.skipThrowForStatus = true;
1406
- }
1407
- return response;
1408
- };
1409
- const App = {
1410
- // ...
1411
- afterResponse: [disableAutoThrowOn456],
1412
- // ...
1413
- };
1414
- ```
1415
-
1416
- For developers using v9.x and below, it's your responsibility to throw an exception for an error response. That means you should call `response.throwForStatus()` or throw an error yourself, likely following the `z.request` call.
1417
-
1418
- This behavior has changed periodically across major versions, which changes how/when you have to worry about handling errors. Here's a diagram to illustrate that:
1419
-
1420
- <!-- diagram source: https://excalidraw.com/#json=stm4O1SLW3ko4FCX9rvsI,6NgRCAK81Cc8M3MuXhNDNA -->
1421
-
1422
- ![](https://cdn.zappy.app/e835d9beca1b6489a065d51a381613f3.png)
1423
-
1424
- Ensure you're handling errors correctly for your platform version. The latest released version is **PACKAGE_VERSION**.
1425
-
1426
- ### HTTP Request Options
1427
-
1428
- [Shorthand requests](#shorthand-http-requests) and [manual requests](#manual-http-requests) support the following HTTP `options`:
1429
-
1430
- * `url`: HTTP url, you can provide it as a separate argument (`z.request(url, options)`) or as part of the `options` object (`z.request({url: url, ...})`).
1431
- * `method`: HTTP method, default is `GET`.
1432
- * `headers`: request headers object, format `{'header-key': 'header-value'}`.
1433
- * `params`: URL query params object, format `{'query-key': 'query-value'}`.
1434
- * `body`: request body, can be a string, buffer, readable stream or plain object. When it is an object/array and the `Content-Type` header is `application/x-www-form-urlencoded` the body will be transformed to query string parameters, otherwise we'll set the header to `application/json; charset=utf-8` and JSON encode the body. Default is `null`.
1435
- * `allowGetBody`: include `body` in `GET` requests. Set to `true` to enable. Default is `false`. Set only if required by the receiving API. See [section 4.3.1 in RFC 7231](https://www.rfc-editor.org/rfc/rfc7231#section-4.3.1).
1436
- * `json`: shortcut object/array/etc. you want to JSON encode into body. Default is `null`.
1437
- * `form`: shortcut object. you want to form encode into body. Default is `null`.
1438
- * `raw`: set this to stream the response instead of consuming it immediately. Default is `false`.
1439
- * `redirect`: set to `manual` to extract redirect headers, `error` to reject redirect, default is `follow`.
1440
- * `follow`: maximum redirect count, set to `0` to not follow redirects. default is `20`.
1441
- * `compress`: support gzip/deflate content encoding. Set to `false` to disable. Default is `true`.
1442
- * `agent`: Node.js `http.Agent` instance, allows custom proxy, certificate etc. Default is `null`.
1443
- * `timeout`: request / response timeout in ms. Set to `0` to disable (OS limit still applies), timeout reset on `redirect`. Default is `0` (disabled).
1444
- * `signal` (_added in v15.14.1_): enables cancelling requests via a timeout set by an `AbortController`. More details in `node-fetch` docs [here](https://www.npmjs.com/package/node-fetch#request-cancellation-with-abortsignal). Default is `null`.
1445
- * `size`: maximum response body size in bytes. Set to `0` to disable. Default is `0` (disabled).
1446
- * `skipThrowForStatus` (_added in v10.0.0_): don't call `response.throwForStatus()` before resolving the request with `response`. See [HTTP Response Object](#http-response-object).
1447
-
1448
- ```js
1449
- const response = await z.request({
1450
- url: 'https://example.com',
1451
- method: 'POST',
1452
- headers: {
1453
- 'Content-Type': 'application/json'
1454
- },
1455
- // only provide body, json or form...
1456
- body: {hello: 'world'}, // or '{"hello": "world"}' or 'hello=world'
1457
- json: {hello: 'world'},
1458
- form: {hello: 'world'},
1459
- // access node-fetch style response.body
1460
- raw: false,
1461
- redirect: 'follow',
1462
- follow: 20,
1463
- compress: true,
1464
- agent: null,
1465
- timeout: 0,
1466
- size: 0,
1467
- })
1468
- ```
1469
-
1470
- ### HTTP Response Object
1471
-
1472
- The response object returned by `z.request([url], options)` supports the following fields and methods:
1473
-
1474
- * `status`: The response status code, i.e. `200`, `404`, etc.
1475
- * `content`: The response content as a String. For Buffer, try `options.raw = true`.
1476
- * `data` (_added in v10.0.0_): The response content as an object if the content is JSON or `application/x-www-form-urlencoded` (`undefined` otherwise).
1477
- * `headers`: Response headers object. The header keys are all lower case.
1478
- * `getHeader(key)`: Retrieve response header, case insensitive: `response.getHeader('My-Header')`
1479
- * `skipThrowForStatus` (_added in v10.0.0_): don't call `throwForStatus()` before resolving the request with this response.
1480
- * `throwForStatus()`: Throws an error if `400 <= statusCode < 600`.
1481
- * `request`: The original request options object (see above).
1482
-
1483
- Additionally, if `request.raw` is `true`, the raw response has the following properties:
1484
-
1485
- * `json()`: Get the response content as an object, if `options.raw = true` and content is JSON (returns a promise). `undefined` in non-raw requests.
1486
- * `body`: A stream available only if you provide `options.raw = true`.
1487
-
1488
- ```js
1489
- const response = await z.request({
1490
- // options
1491
- });
1492
-
1493
- // A bunch of examples for demonstration
1494
- response.status;
1495
- response.headers['Content-Type'];
1496
- response.getHeader('content-type');
1497
- response.request; // original request options
1498
- response.throwForStatus();
1499
-
1500
- if (options.raw === false) { // (default)
1501
- // If you're core v10+
1502
- response.data; // same as...
1503
- z.JSON.parse(response.content); // or...
1504
- querystring.parse(response.content);
1505
-
1506
- // If you're core v9 or older...
1507
- response.json; // same as
1508
- z.JSON.parse(response.content);
1509
- } else {
1510
- const buf = await response.buffer();
1511
- buf.toString();
1512
-
1513
- const text = await response.text();
1514
-
1515
- const json = await response.json();
1516
-
1517
- response.body.pipe(otherStream);
1518
- }
1519
- ```
1520
-
1521
- ## Dehydration
1522
-
1523
- Dehydration, and its counterpart Hydration, is a tool that can lazily load data that might be otherwise expensive to retrieve aggressively.
1524
-
1525
- * **Dehydration** - think of this as "make a pointer", you control the creation of pointers with `z.dehydrate(func, inputData)` (or `z.dehydrateFile(func, inputData)` for files). This usually happens in a trigger step.
1526
- * **Hydration** - think of this as an automatic step that "consumes a pointer" and "returns some data", Zapier does this automatically behind the scenes. This usually happens in an action step.
1527
-
1528
- > This is very common when [Stashing Files](#stashing-files) - but that isn't their only use!
1529
-
1530
- The method `z.dehydrate(func, inputData)` has two required arguments:
1531
-
1532
- * `func` - the function to call to fetch the extra data. Can be any raw `function`, defined in the file doing the dehydration or imported from another part of your app. You must also register the function in the app's `hydrators` property. Note that since v10.1.0, the maximum payload size to pass to `z.dehydrate` / `z.dehydrateFile` is 6KB.
1533
- * `inputData` - this is an object that contains things like a `path` or `id` - whatever you need to load data on the other side
1534
- * A known limitation of hydration is a 5 minute cache if the hydration call is made with identical `inputData` within that timeframe. To workaround this cache for records triggering hydration in close succession, include a unique value in the `inputData`, for example a `timestamp` in addition to the record `id`.
1535
-
1536
- > **Why do I need to register my functions?** Because of how JavaScript works with its module system, we need an explicit handle on the function that can be accessed from the App definition without trying to "automagically" (and sometimes incorrectly) infer code locations.
1537
-
1538
- Here is an example that pulls in extra data for a movie:
1539
-
1540
- ```js
1541
- [insert-file:./snippets/dehydration.js]
1542
- ```
1543
-
1544
- And in future steps of the Zap - if Zapier encounters a pointer as returned by `z.dehydrate(func, inputData)` - Zapier will tie it back to your app and pull in the data lazily.
1545
-
1546
- > **Why can't I just load the data immediately?** Isn't it easier? In some cases it can be - but imagine an API that returns 100 records when polling - doing 100x `GET /id.json` aggressive inline HTTP calls when 99% of the time Zapier doesn't _need_ the data yet is wasteful.
1547
-
1548
- ### Merging Hydrated Data
1549
-
1550
- As you've seen, the usual call to dehydrate will assign the result to an object property:
1551
-
1552
- ```js
1553
- movie.details = z.dehydrate(getMovieDetails, { id: movie.id });
1554
- ```
1555
-
1556
- In this example, all of the movie details will be located in the `details` property (e.g. `details.releaseDate`) after hydration occurs. But what if you want these results available at the top-level (e.g. `releaseDate`)? Zapier supports a specific keyword for this scenario:
1557
-
1558
- ```js
1559
- movie.$HOIST$ = z.dehydrate(getMovieDetails, { id: movie.id });
1560
- ```
1561
-
1562
- Using `$HOIST$` as the key will signal to Zapier that the results should be merged into the object containing the `$HOIST$` key. You can also use this to merge your hydrated data into a property containing "partial" data that exists before dehydration occurs:
1563
-
1564
- ```js
1565
- movie.details = {
1566
- title: movie.title,
1567
- $HOIST$: z.dehydrate(getMovieDetails, { id: movie.id })
1568
- };
1569
- ```
1570
-
1571
- ### File Dehydration
1572
-
1573
- *Added in v7.3.0.*
1574
-
1575
- The method `z.dehydrateFile(func, inputData)` allows you to download a file lazily. It takes the same arguments as `z.dehydrate(func, inputData)` does, but is recommended when the data is a file.
1576
-
1577
- An example can be found in the [Stashing Files](#stashing-files) section.
1578
-
1579
- What makes `z.dehydrateFile` different from `z.dehydrate` has to do with efficiency and when Zapier chooses to hydrate data. Knowing which pointers give us back files helps us delay downloading files until it's absolutely necessary. Not only will it help avoid unnecessary file downloads, it can also prevent errors if the file has a limited availability. (Stashing files, described below, can also help with that situation.)
1580
-
1581
- A good example is when users are creating Zaps in the Zap Editor. If a pointer is made by `z.dehydrate`, the Zap Editor will hydrate the data immediately after pulling in samples. This allows users to map fields from the hydrated data into the subsequent steps of the Zap. If, however, the pointer is made by `z.dehydrateFile`, the Zap Editor will wait to hydrate the file, and will display a placeholder instead. There's nothing inside binary file data for users to map in the subsequent steps.
1582
-
1583
- > `z.dehydrateFile(func, inputData)` was added in v7.3.0. We used to recommend using `z.dehydrate(func, inputData)` for files, but we now recommend changing it to `z.dehydrateFile(func, inputData)` for a better user experience.
1584
-
1585
- ## Stashing Files
1586
-
1587
- It can be expensive to download and stream files or they can require complex handshakes to authorize downloads - so we provide a helpful stash routine that will take any `String`, `Buffer` or `Stream` and return a URL file pointer suitable for returning from triggers, searches, creates, etc.
1588
-
1589
- The interface `z.stashFile(bufferStringStream, [knownLength], [filename], [contentType])` takes a single required argument - the extra three arguments will be automatically populated in most cases. Here's a full example:
1590
-
1591
- ```js
1592
- const content = 'Hello world!';
1593
- const url = await z.stashFile(content, content.length, 'hello.txt', 'text/plain');
1594
- z.console.log(url);
1595
- // https://zapier-dev-files.s3.amazonaws.com/cli-platform/f75e2819-05e2-41d0-b70e-9f8272f9eebf
1596
- ```
1597
-
1598
- Most likely you'd want to stream from another URL - note the usage of `z.request({raw: true})`:
1599
-
1600
- ```js
1601
- const fileRequest = z.request({url: 'https://example.com/file.pdf', raw: true});
1602
- const url = await z.stashFile(fileRequest); // knownLength and filename will be sniffed from the request. contentType will be binary/octet-stream
1603
- z.console.log(url);
1604
- // https://zapier-dev-files.s3.amazonaws.com/cli-platform/74bc623c-d94d-4cac-81f1-f71d7d517bc7
1605
- ```
1606
-
1607
- > Note: you should only be using `z.stashFile()` in a hydration method or a hook trigger's `perform` if you're sending over a short-lived URL to a file. Otherwise, it can be very expensive to stash dozens of files in a polling call - for example!
1608
-
1609
- See a full example with dehydration/hydration wired in correctly:
1610
-
1611
- ```js
1612
- [insert-file:./snippets/stash-file.js]
1613
- ```
1614
-
1615
- > To create a new integration for handling files, run `zapier init [your app name] --template files`. You can also check out our working example app [here](https://github.com/zapier/zapier-platform/tree/main/example-apps/files).
1616
-
1617
-
1618
- ## Logging
1619
-
1620
- To view the logs for your application, use the `zapier logs` command.
1621
-
1622
- There are three types of logs for a Zapier app:
1623
-
1624
- * `http`: logged automatically by Zapier on HTTP requests
1625
- * `bundle`: logged automatically on every method execution
1626
- * `console`: manual logs via `z.console.log()` statements ([see below for details](#console-logging))
1627
-
1628
- Note that by default, this command will only fetch logs associated to your user.
1629
-
1630
- For advanced logging options, including the option to fetch logs for other users or specific app versions, look at the help for the logs command:
1631
-
1632
- ```bash
1633
- zapier help logs
1634
- ```
1635
-
1636
- ### Console Logging
1637
-
1638
- To manually print a log statement in your code, use `z.console.log`:
1639
-
1640
- ```js
1641
- z.console.log('Here are the input fields', bundle.inputData);
1642
- ```
1643
-
1644
- The `z.console` object has all the same methods and works just like the Node.js [`Console`](https://nodejs.org/docs/latest-v14.x/api/console.html) class - the only difference is we'll log to our distributed datastore and you can view the logs via `zapier logs` (more below).
1645
-
1646
- ### Viewing Console Logs
1647
-
1648
- To see your `z.console.log` logs, do:
1649
-
1650
- ```bash
1651
- zapier logs --type=console
1652
- ```
1653
-
1654
- ### Viewing Bundle Logs
1655
-
1656
- To see the bundle logs, do:
1657
-
1658
- ```bash
1659
- zapier logs --type=bundle
1660
- ```
1661
-
1662
- ### HTTP Logging
1663
-
1664
- If you are using [shorthand HTTP requests](#shorthand-http-requests) or the `z.request()` method that we provide, HTTP logging is handled automatically for you. For example:
1665
-
1666
- ```js
1667
- z.request('https://57b20fb546b57d1100a3c405.mockapi.io/api/recipes')
1668
- .then((res) => {
1669
- // do whatever you like, this request is already getting logged! :-D
1670
- return res;
1671
- })
1672
- ```
1673
-
1674
- HTTP logging will often work with other methods of making requests as well, but if you're using another method and having trouble seeing logs, try using `z.request()`.
1675
-
1676
- ### Viewing HTTP Logs
1677
-
1678
- To see the HTTP logs, do:
1679
-
1680
- ```bash
1681
- zapier logs --type=http
1682
- ```
1683
- To see detailed HTTP logs, including data such as headers and request and response bodies, do:
1684
-
1685
- ```bash
1686
- zapier logs --type=http --detailed
1687
- ```
1688
-
1689
-
1690
- ## Error Handling
1691
-
1692
- APIs are not always available. Users do not always input data correctly to
1693
- formulate valid requests. Thus, it is a good idea to write apps defensively and
1694
- plan for 4xx and 5xx responses from APIs. Without proper handling, errors often
1695
- have incomprehensible messages for end users, or possibly go uncaught.
1696
-
1697
- Zapier provides a couple of tools to help with error handling. First is the
1698
- `afterResponse` middleware ([docs](#using-http-middleware)), which provides a hook for
1699
- processing all responses from HTTP calls. Second is `response.throwForStatus()`
1700
- ([docs](#http-response-object)), which throws an error if the response status indicates
1701
- an error (status >= 400). Since v10.0.0, we automatically call this method before returning the
1702
- response, unless you set `skipThrowForStatus` on the request or response object. The
1703
- last tool is the collection of errors in `z.errors` ([docs](#zerrors)), which control
1704
- the behavior of Zaps when various kinds of errors occur.
1705
-
1706
- ### General Errors
1707
-
1708
- Errors due to a misconfiguration in a user's Zap should be handled in your app
1709
- by throwing `z.errors.Error` with a user-friendly message and optional error and
1710
- status code. Typically, this will be prettifying 4xx responses or APIs that return
1711
- errors as 200s with a payload that describes the error.
1712
-
1713
- Example: `throw new z.errors.Error('Contact name is too long.', 'InvalidData', 400);`
1714
-
1715
- > `z.errors.Error` was added in v9.3.0. If you're on an older version of `zapier-platform-core`, throw a standard JavaScript `Error` instead, such as `throw new Error('A user-friendly message')`.
1716
-
1717
- A couple best practices to keep in mind:
1718
-
1719
- * Elaborate on terse messages. "not_authenticated" -> "Your API Key is invalid. Please reconnect your account."
1720
- * If the error calls out a specific field, surface that information to the user. "Provided data is invalid" -> "Contact name is invalid"
1721
- * If the error provides details about why a field is invalid, add that in too! "Contact name is invalid" -> "Contact name is too long"
1722
- * The second, optional argument should be a code that a computer could use to identify the type of error.
1723
- * The last, optional argument should be the HTTP status code, if any.
1724
-
1725
- The code and status can be used by us to provide relevant troubleshooting to the
1726
- user when we communicate the error.
1727
-
1728
- Note that if a Zap raises too many error messages it will be automatically
1729
- turned off, so only use these if the scenario is truly an error that needs to
1730
- be fixed.
1731
-
1732
- ### Halting Execution
1733
-
1734
- Any operation can be interrupted or "halted" (not success, not error, but
1735
- stopped for some specific reason) with a `HaltedError`. You might find yourself
1736
- using this error in cases where a required pre-condition is not met. For instance,
1737
- in a create to add an email address to a list where duplicates are not allowed,
1738
- you would want to throw a `HaltedError` if the Zap attempted to add a duplicate.
1739
- This would indicate failure, but it would be treated as a soft failure.
1740
-
1741
- Unlike throwing `z.errors.Error`, a Zap will never by turned off when this error is thrown
1742
- (even if it is raised more often than not).
1743
-
1744
- Example: `throw new z.errors.HaltedError('Your reason.');`
1745
-
1746
- ### Stale Authentication Credentials
1747
-
1748
- For apps that require manual refresh of authorization on a regular basis, Zapier
1749
- provides a mechanism to notify users of expired credentials. With the
1750
- `ExpiredAuthError`, the current operation is interrupted and a predefined email
1751
- is sent out asking the user to refresh the credentials. While the auth is
1752
- disconnected, Zap runs will not be executed, to prevent more calls with expired
1753
- credentials. (The runs will be
1754
- [Held](https://help.zapier.com/hc/en-us/articles/8496291148685-View-and-manage-your-Zap-history#held-0-3),
1755
- and the user will be able to replay them after reconnecting.)
1756
-
1757
- Example: `throw new z.errors.ExpiredAuthError('You must manually reconnect this auth.');`
1758
-
1759
- For apps that use OAuth2 with `autoRefresh: true` or Session Auth, `core` injects
1760
- a built-in `afterResponse` middleware that throws an error when the response status
1761
- is 401. The error will signal Zapier to refresh the credentials and then retry the
1762
- failed operation. You can also throw this error manually if your server doesn't use the 401 status or you want to trigger an auth refresh even if the credentials aren't stale.
1763
-
1764
- Example: `throw new z.errors.RefreshAuthError();`
1765
-
1766
- ### Handling Throttled Requests
1767
-
1768
- Since v11.2.0, there are two types of errors that can cause Zapier to throttle an operation and retry at a later time.
1769
- This is useful if the API you're interfacing with reports it is receiving too many requests, often indicated by
1770
- receiving a response status code of 429.
1771
-
1772
- If a response receives a status code of 429 and is not caught, Zapier will re-attempt the operation after a delay.
1773
- The delay can be customized by the server response containing a specific
1774
- [Retry-After](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header in your error response or with a specified time delay in seconds using a `ThrottledError`:
1775
-
1776
- ```js
1777
- const yourAfterResponse = (resp) => {
1778
- if (resp.status === 429) {
1779
- throw new z.errors.ThrottledError('message here', 60); // Zapier will retry in 60 seconds
1780
- }
1781
- return resp;
1782
- };
1783
- ```
1784
- Instead of a user’s Zap erroring and halting, the request will be repeatedly retried at the specified time.
1785
-
1786
- For throttled requests that occur during processing of a webhook trigger's perform, before results are produced; there is a max retry delay of 300 seconds and a default delay of 60 seconds if none is specified. For webhook processing only, if a request during the retry attempt is also throttled, it will not be re-attempted again.
1787
-
1788
- ## Testing
1789
-
1790
- You can write unit tests for your Zapier integration that run locally, outside of the Zapier editor.
1791
- You can run these tests in a CI tool like [Travis](https://travis-ci.com/).
1792
-
1793
- ### Writing Unit Tests
1794
-
1795
- From v10 of `zapier-platform-cli`, we recommend using the [Jest](https://jestjs.io/) testing framework. After running `zapier init` you should find an example test to start from in the `test` directory.
1796
-
1797
- > Note: On v9, the recommendation was [Mocha](https://mochajs.org/). You can still use Mocha if you prefer.
1798
-
1799
- ```js
1800
- [insert-file:./snippets/jest-test.js]
1801
- ```
1802
-
1803
- ### Using the `z` Object in Tests
1804
-
1805
- Introduced in `core@11.1.0`, `appTester` can now run arbitrary functions:
1806
-
1807
- ```js
1808
- [insert-file:./snippets/jest-adhoc-func.js]
1809
- ```
1810
-
1811
- ### Mocking Requests
1812
-
1813
- It's useful to test your code without actually hitting any external services. [Nock](https://github.com/node-nock/nock) is a Node.js utility that intercepts requests before they ever leave your computer. You can specify a response code, body, headers, and more. It works out of the box with `z.request` by setting up your `nock` before calling `appTester`.
1814
-
1815
- ```js
1816
- [insert-file:./snippets/jest-mocked-test.js]
1817
- ```
1818
-
1819
- Here's more info about nock and its usage in the [README](https://github.com/node-nock/nock/blob/master/README.md).
1820
-
1821
- ### Running Unit Tests
1822
-
1823
- To run all your tests do:
1824
-
1825
- ```bash
1826
- zapier test
1827
- ```
1828
-
1829
- > You can also go direct with `npm test` or `node_modules/.bin/jest`.
1830
-
1831
- ### Testing & Environment Variables
1832
-
1833
- The best way to store sensitive values (like API keys, OAuth secrets, or passwords) is in an `.env` (or `.environment`, see below note) file ([learn more](https://github.com/motdotla/dotenv#faq)). Then, you can include the following before your tests run:
1834
-
1835
- ```js
1836
- const zapier = require('zapier-platform-core');
1837
- zapier.tools.env.inject(); // inject() can take a filename; defaults to ".env"
1838
-
1839
- // now process.env has all the values in your .env file
1840
- ```
1841
-
1842
- > `.env` is the new recommended name for the environment file since v5.1.0. The old name `.environment` is deprecated but will continue to work for backward compatibility.
1843
-
1844
- > Remember: **NEVER** add your secrets file to version control!
1845
-
1846
- Additionally, you can provide them dynamically at runtime:
1847
-
1848
- ```bash
1849
- CLIENT_ID=1234 CLIENT_SECRET=abcd zapier test
1850
- ```
1851
-
1852
- Or, `export` them explicitly and place them into the environment:
1853
-
1854
- ```bash
1855
- export CLIENT_ID=1234
1856
- export CLIENT_SECRET=abcd
1857
- zapier test
1858
- ```
1859
-
1860
- ### Testing in Your CI
1861
-
1862
- Whether you use Travis, Circle, Jenkins, or another service, we aim to make it painless to test in an automated environment.
1863
-
1864
- Behind the scenes `zapier test` does a standard `npm test`, which could be [Jest](https://jestjs.io/) or [Mocha](https://mochajs.org/), based on your project setup.
1865
-
1866
- This makes it straightforward to integrate into your testing interface. For example, if you want to test with [Travis CI](https://travis-ci.com/), the `.travis.yml` would look something like this:
1867
-
1868
- ```yaml
1869
- language: node_js
1870
- node_js:
1871
- - "LAMBDA_VERSION"
1872
- before_script: npm install -g zapier-platform-cli
1873
- script: CLIENT_ID=1234 CLIENT_SECRET=abcd zapier test
1874
- ```
1875
-
1876
- You can substitute `zapier test` with `npm test`, or a direct call to `node_modules/.bin/jest`. We recommend putting environment variables directly into the configuration screens Jenkins, Travis, or other services provide.
1877
-
1878
- Alternatively to reading the deploy key from root (the default location), you may set the `ZAPIER_DEPLOY_KEY` environment variable to run privileged commands without the human input needed for `zapier login`. We suggest encrypting your deploy key in the manner your CI provides (such as [these instructions](https://docs.travis-ci.com/user/environment-variables/#Defining-encrypted-variables-in-.travis.yml), for Travis).
1879
-
1880
- ### Debugging Tests
1881
-
1882
- Sometimes tests aren't enough, and you may want to step through your code and set breakpoints. The testing suite is a regular Node.js process, so debugging it doesn't take anything special. Because we recommend `jest` for testing, these instructions will outline steps for debugging w/ jest, but other test runners will work similarly. You can also refer to [Jest's own docs on the subject](https://jestjs.io/docs/en/troubleshooting#tests-are-failing-and-you-dont-know-why).
1883
-
1884
- To start, add the following line to the `scripts` section of your `package.json`:
1885
-
1886
- ```
1887
- "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand"
1888
- ```
1889
-
1890
- This will tell `node` to inspect the `jest` processes, which is exactly what we need.
1891
-
1892
- Next, add a `debugger;` statement somewhere in your code, probably in a `perform` method:
1893
-
1894
- ```js
1895
- // triggers on a new pizza with a certain tag
1896
- const perform = async (z, bundle) => {
1897
- const response = await z.request({
1898
- url: "https://jsonplaceholder.typicode.com/posts",
1899
- params: {
1900
- tag: bundle.inputData.tagName,
1901
- },
1902
- });
1903
- debugger;
1904
- // this should return an array of objects
1905
- return response.data;
1906
- };
1907
- ```
1908
-
1909
- This creates a _breakpoint_ while `inspect`ing, or a starting point for our manual inspection.
1910
-
1911
- Next, you'll need an inspection client. The most available one is probably the Google Chrome browser, but there are [lots of options](https://nodejs.org/en/docs/guides/debugging-getting-started/#inspector-clients). We'll use Chrome for this example. In your terminal (and in your integration's root directory), run `yarn test:debug` (or `npm run test:debug`). You should see the following:
1912
-
1913
- ```
1914
- % yarn test:debug
1915
- yarn run v1.22.10
1916
- $ node --inspect-brk node_modules/.bin/jest --runInBand
1917
- Debugger listening on ws://127.0.0.1:9229/5edaab3c-a1d3-45e4-b374-0536095c559b
1918
- For help, see: https://nodejs.org/en/docs/inspector
1919
- ```
1920
-
1921
- Now in Chrome, go to chrome://inspect. Make sure `Discover Network Targets` is checked and you should see a path to your `jest` file on your local machine:
1922
-
1923
- ![](https://cdn.zappy.app/e2836d2950e1f8a03e3621a22452c3cd.png)
1924
-
1925
- Click `inspect`. A new window will open. Next, click the little blue arrow in the top right to actually run the code:
1926
-
1927
- ![](https://cdn.zappy.app/a64e7963a7090e9730d9c8e7b3595a6a.png)
1928
-
1929
- After a few seconds, you'll see your code, the `debugger` statement, and info about the current environment on the right panel. You should see familiar data in the `Locals` section, such as the `response` variable, and the `z` object.
1930
-
1931
- ![](https://cdn.zappy.app/4bfdfe079a344ab7aced64ad7728bc6a.png)
1932
-
1933
- Debugging combined with thorough unit tests will hopefully equip you in keeping your Zapier integration in smooth working order.
1934
-
1935
- ## Using `npm` Modules
1936
-
1937
- Use `npm` modules just like you would use them in any other node app, for example:
1938
-
1939
- ```bash
1940
- npm install --save jwt
1941
- ```
1942
-
1943
- And then `package.json` will be updated, and you can use them like anything else:
1944
-
1945
- ```js
1946
- const jwt = require('jwt');
1947
- ```
1948
-
1949
- During the `zapier build` or `zapier push` step - we'll copy all your code to a temporary folder and do a fresh re-install of modules.
1950
-
1951
- > Note: If your package isn't being pushed correctly (IE: you get "Error: Cannot find module 'whatever'" in production), try adding the `--disable-dependency-detection` flag to `zapier push`.
1952
-
1953
- > Note 2: You can also try adding a `includeInBuild` array property (with paths to include, which will be evaluated to RegExp, with a case insensitive flag) to your `.zapierapprc` file, to make it look like:
1954
-
1955
- ```json
1956
- {
1957
- "id": 1,
1958
- "key": "App1",
1959
- "includeInBuild": [
1960
- "test.txt",
1961
- "testing.json"
1962
- ]
1963
- }
1964
-
1965
- ```
1966
-
1967
- > Warning: Do not use compiled libraries unless you run your build on the AWS AMI `ami-4fffc834`, or follow the Docker instructions below.
1968
-
1969
- ## Building Native Packages with Docker
1970
-
1971
- Unfortunately if you are developing on a macOS or Windows box you won't be able to build native libraries locally. If you try and push locally build native modules, you'll get runtime errors during usage. However, you can use Docker and Docker Compose to do this in a pinch. Make sure you have all the necessary Docker programs installed and follow along.
1972
-
1973
- First, create your `Dockerfile`:
1974
-
1975
- ```Dockerfile
1976
- FROM amazonlinux:2017.03.1.20170812
1977
-
1978
- RUN yum install zip findutils wget gcc44 gcc-c++ libgcc44 cmake -y
1979
-
1980
- RUN wget https://nodejs.org/dist/v8.10.0/node-v8.10.0.tar.gz && \
1981
- tar -zxvf node-v8.10.0.tar.gz && \
1982
- cd node-v8.10.0 && \
1983
- ./configure && \
1984
- make && \
1985
- make install && \
1986
- cd .. && \
1987
- rm -rf node-v8.10.0 node-v8.10.0.tar.gz
1988
-
1989
- RUN npm i -g zapier-platform-cli
1990
-
1991
- WORKDIR /app
1992
- ```
1993
-
1994
- And finally, create your `docker-compose.yml` file:
1995
-
1996
- ```yml
1997
- version: '3.4'
1998
-
1999
- services:
2000
- pusher:
2001
- build: .
2002
- volumes:
2003
- - .:/app
2004
- - node_modules:/app/node_modules:delegated
2005
- - ~/.zapierrc:/root/.zapierrc
2006
- command: 'bash -c "npm i && zapier push"'
2007
- environment:
2008
- ZAPIER_DEPLOY_KEY: ${ZAPIER_DEPLOY_KEY}
2009
-
2010
- volumes:
2011
- node_modules:
2012
- ```
2013
-
2014
- > Note: Watch out for your `package-lock.json` file, if it exists for local install it might incorrectly pin a native version.
2015
-
2016
- Now you should be able to run `docker-compose run pusher` and see the build and push successfully complete!
2017
-
2018
-
2019
- ## Using Transpilers
2020
-
2021
- If you would like to use a transpiler like `babel`, you can add a script named `_zapier-build` to your `package.json`, which will be run during `zapier build`,
2022
- `zapier push`, and `zapier upload`. See the following example:
2023
-
2024
- ```json
2025
- {
2026
- "scripts": {
2027
- "zapier-dev": "babel src --out-dir lib --watch",
2028
- "_zapier-build": "babel src --out-dir lib"
2029
- }
2030
- }
2031
- ```
2032
-
2033
- Then, you can have your fancy ES7 code in `src/*` and a root `index.js` like this:
2034
-
2035
- ```js
2036
- module.exports = require('./lib');
2037
- ```
2038
-
2039
- And work with commands like this:
2040
-
2041
- ```bash
2042
- # watch and recompile
2043
- npm run zapier-dev
2044
-
2045
- # tests should work fine
2046
- zapier test
2047
-
2048
- # every build ensures a fresh build
2049
- zapier push
2050
- ```
2051
-
2052
- There are a lot of details left out - check out the full example app [here](https://github.com/zapier/zapier-platform/tree/main/example-apps/babel).
2053
-
2054
- > We recommend using `zapier init .` to create an app - you’ll be presented with a list of currently available example templates to start with.
2055
-
2056
- ## FAQs
2057
-
2058
- ### Why doesn't Zapier support newer versions of Node.js?
2059
-
2060
- We run your code on AWS Lambda, which only supports a few [versions](https://docs.aws.amazon.com/lambda/latest/dg/programming-model.html) of Node. Sometimes that doesn't include the latest version. Additionally, with thousands of apps running on the Zapier platform, we have to be sure upgrading to the latest Node version will not have a negative impact.
2061
-
2062
- ### How do I manually set the Node.js version to run my app with?
2063
-
2064
- Update your `zapier-platform-core` dependency in `package.json`. Each major version ties to a specific version of Node.js. You can find the mapping [here](https://github.com/zapier/zapier-platform/blob/main/packages/cli/src/version-store.js). We only support the version(s) supported by [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/programming-model.html).
2065
-
2066
- **IMPORTANT CAVEAT**: AWS periodically deprecates Node versions as they reach EOL. They announce this[on their blog](https://aws.amazon.com/blogs/developer/node-js-6-is-approaching-end-of-life-upgrade-your-aws-lambda-functions-to-the-node-js-10-lts/). Similar info and dates are available on [github](https://github.com/nodejs/Release). Well before this date, we'll have a version of `core` that targets the newer Node version.
2067
-
2068
- If you don't upgrade before the cutoff date, there's a chance that AWS will throw an error when attempting to run your app's code. If that's the case, we'll instead run it under the oldest Node version still supported. All that is to say, **we may run your code on a newer version of Node.js than you intend** if you don't update your app's dependencies periodically.
2069
-
2070
- ### When to use placeholders or curlies?
2071
-
2072
- You will see both [template literal placeholders](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Expression_interpolation) `${var}` and (double) "curlies" `{{var}}` used in examples.
2073
-
2074
- In general, use `${var}` within functions and use `{{var}}` anywhere else.
2075
-
2076
- Placeholders get evaluated as soon as the line of code is evaluated. This means that if you use `${process.env.VAR}` in a trigger configuration, `zapier push` will substitute it with your local environment's value for `VAR` when it builds your app and the value set via `zapier env:set` will not be used.
2077
-
2078
- > If you're not familiar with [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), know that `const val = "a" + b + "c"` is essentially the same as <code>const val = &#96;a${b}c&#96;</code>.
2079
-
2080
- ### Does Zapier support XML (SOAP) APIs?
2081
-
2082
- Not natively, but it can! Users have reported that the following `npm` modules are compatible with the CLI Platform:
2083
-
2084
- * [pixl-xml](https://github.com/jhuckaby/pixl-xml)
2085
- * [xml2js](https://github.com/Leonidas-from-XIV/node-xml2js)
2086
- * [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser)
2087
-
2088
- Since core v10, it's possible for [shorthand requests](#shorthand-http-requests) to parse XML. Use an `afterResponse` [middleware](#using-http-middleware) that sets `response.data` to the parsed XML:
2089
-
2090
- ```js
2091
- [insert-file:./snippets/xml.js]
2092
- ```
2093
-
2094
- ### Is it possible to iterate over pages in a polling trigger?
2095
-
2096
- Yes, though there are caveats. Your entire function only gets 30 seconds to run. HTTP requests are costly, so paging through a list may time out (which you should avoid at all costs).
2097
-
2098
- ```js
2099
- [insert-file:./snippets/paging-poll.js]
2100
- ```
2101
-
2102
- If you need to do more requests conditionally based on the results of an HTTP call (such as the "next URL" param or similar value), using `async/await` (as shown in the example below) is a good way to go. If you go this route, only page as far as you need to. Keep an eye on the polling [guidelines](https://zapier.com/developer/documentation/v2/deduplication/), namely the part about only iterating until you hit items that have probably been seen in a previous poll.
2103
-
2104
- ```js
2105
- [insert-file:./snippets/async-polling.js]
2106
- ```
2107
-
2108
- ### How do search-powered fields relate to dynamic dropdowns and why are they both required together?
2109
-
2110
- To understand search-powered fields, we have to have a good understanding of dynamic dropdowns.
2111
-
2112
- When users are selecting specific resources (for instance, a Google Sheet), it's important they're able to select the exact sheet they want. Instead of referencing the sheet by name (which may change), we match via `id` instead. Rather than directing the user copy and paste an id for every item they might encounter, there is the notion of a **dynamic dropdown**. A dropdown is a trigger that returns a list of resources. It can pull double duty and use its results to power another trigger, search, or action in the same app. It provides a list of ids with labels that show the item's name:
2113
-
2114
- ![](https://cdn.zappy.app/2d7eeda63ff34b70f1d1788de0117181.png)
2115
-
2116
- The field's value reaches your app as an id. You define this connection with the `dynamic` property, which is a string: `trigger_key.id_key.label_key`. This approach works great if the user setting up the Zap always wants the Zap to use the same spreadsheet. They specify the id during setup and the Zap runs happily.
2117
-
2118
- **Search fields** take this connection a step further. Rather than set the spreadsheet id at setup, the user could precede the action with a search field to make the id dynamic. For instance, let's say you have a different spreadsheet for every day of the week. You could build the following zap:
2119
-
2120
- 1. Some Trigger
2121
- 2. Calculate what day of the week it is today (Code)
2122
- 3. Find the spreadsheet that matches the day from Step 2
2123
- 4. Update the spreadsheet (with the id from step 3) with some data
2124
-
2125
- If the connection between steps 3 and 4 is a common one, you can indicate that in your field by specifying `search` as a `search_key.id_key`. When paired **with a dynamic dropdown**, this will add a button to the editor that will add the search step to the user's Zap and map the id field correctly.
2126
-
2127
- ![](https://cdn.zappy.app/081e63141ff05c131dadb8ebbea727b0.png)
2128
-
2129
- This is paired most often with "update" actions, where a required parameter will be a resource id.
2130
-
2131
- <a id="paging"></a>
2132
- ### What's the deal with pagination? When is it used and how does it work?
2133
-
2134
- Paging is **only used when a trigger is part of a dynamic dropdown**. Depending on how many items exist and how many are returned in the first poll, it's possible that the resource the user is looking for isn't in the initial poll. If they hit the "see more" button, we'll increment the value of `bundle.meta.page` and poll again.
2135
-
2136
- Paging is a lot like a regular trigger except the range of items returned is dynamic. The most common example of this is when you can pass a `offset` parameter:
2137
-
2138
- ```js
2139
- const perform = async (z, bundle) => {
2140
- const response = await z.request({
2141
- url: 'https://example.com/api/list.json',
2142
- params: {
2143
- limit: 100,
2144
- offset: 100 * bundle.meta.page
2145
- }
2146
- });
2147
- return response.data; // or response.json you're using core v9 or older
2148
- };
2149
- ```
2150
-
2151
- If your API uses cursor-based paging instead of an offset, you can use `z.cursor.get` and `z.cursor.set`:
2152
-
2153
- ```js
2154
- [insert-file:./snippets/paging-cursor.js]
2155
- ```
2156
-
2157
- Cursors are stored per-zap and last about an hour. Per the above, make sure to only include the cursor if `bundle.meta.page > 0`, so you don't accidentally reuse a cursor from a previous poll.
2158
-
2159
- Lastly, you need to set `canPaginate` to `true` in your polling definition (per the [schema](https://github.com/zapier/zapier-platform/blob/main/packages/schema/docs/build/schema.md#basicpollingoperationschema)) for the `z.cursor` methods to work as expected.
2160
-
2161
- <a id="dedup"></a>
2162
- ### How does deduplication work?
2163
-
2164
- Each time a polling Zap runs, Zapier extracts a unique "primary key" for each item in the response. Zapier needs to decide which of the items should trigger the Zap. To do this, we compare the primary keys to all those we've seen before, trigger on new objects, and update the list of seen primary keys. When a Zap is turned on, we initialize the list of seen primary keys with a single poll. When it's turned off, we clear that list. For this reason, it's important that calls to a polling endpoint always return the newest items.
2165
-
2166
- For example, the initial poll returns objects 4, 5, and 6 (where a higher primary key is newer). If a later poll increases the limit and returns objects 1-6, then 1, 2, and 3 will be (incorrectly) treated like new objects.
2167
-
2168
- By default, the primary key is the item's `id` field. Since v15.6.0, you can customize the primary key by setting `primary` to true in `outputFields`.
2169
-
2170
- There's a more in-depth explanation [here](https://platform.zapier.com/build/deduplication).
2171
-
2172
- ### Why are my triggers complaining if I don't provide an explicit `id` field?
2173
-
2174
- For deduplication to work, we need to be able to identify and use a unique field. In older, legacy Zapier Web Builder apps, we guessed if `id` wasn't present. In order to ensure we don't guess wrong, we now require that the developers send us an `id` field. If your objects have a differently-named unique field, feel free to adapt this snippet and ensure this test passes:
2175
-
2176
- ```js
2177
- // ...
2178
- let items = response.data.items; // or response.json.items if you're using core v9 or older
2179
- return items.map((item) => {
2180
- item.id = item.contactId;
2181
- return item;
2182
- });
2183
- ```
2184
-
2185
- Since v15.6.0, instead of using the default `id` field, you can also define one or more `outputFields` as `primary`. For example:
2186
-
2187
- ```js
2188
- {
2189
- triggers: {
2190
- recipe: {
2191
- operation: {
2192
- outputField: [
2193
- { key: 'userId', primary: true },
2194
- { key: 'slug', primary: true },
2195
- { key: 'name' }
2196
- ]
2197
- }
2198
- }
2199
- }
2200
- }
2201
- ```
2202
-
2203
- will tell Zapier to use `(userId, slug)` as the unique primary key to deduplicate items when running a polling trigger.
2204
-
2205
- **Limitation:** The `primary` option currently doesn't support mixing top-level fields with nested fields that use double underscores in their keys. For example, if you set `primary: true` on both `id` and `user__id`, the `primary` setting on the `user__id` field will be ignored; only `id` will be used for deduplication. However, if all the `primary` fields are all nested, such as `user__id` + `user__name`, it will work as expected.
2206
-
2207
- ### Node X No Longer Supported
2208
-
2209
- If you're seeing errors like the following:
2210
-
2211
- ```
2212
- InvalidParameterValueException An error occurred (InvalidParameterValueException) when calling the CreateFunction operation: The runtime parameter of nodejs6.10 is no longer supported for creating or updating AWS Lambda functions. We recommend you use the new runtime (nodejsX.Y) while creating or updating functions.
2213
- ```
2214
-
2215
- ... then you need to update your `zapier-platform-core` dependency to a non-deprecated version that uses a newer version of Node.js. Complete the following instructions as soon as possible:
2216
-
2217
- 1. Edit `package.json` to depend on a later major version of `zapier-platform-core`. There's a list of all breaking changes (marked with a :exclamation:) in the [changelog](https://github.com/zapier/zapier-platform/blob/main/CHANGELOG.md).
2218
- 2. Increment the `version` property in `package.json`
2219
- 3. Ensure you're using version `LAMBDA_VERSION` (or greater) of node locally (`node -v`). Use [nvm](https://github.com/nvm-sh/nvm) to use a different one if need be.
2220
- 4. Run `rm -rf node_modules && npm i` to get a fresh copy of everything
2221
- 5. Run `zapier test` to ensure your tests still pass
2222
- 6. Run `zapier push`
2223
- 7. Run `zapier promote YOUR_NEW_VERSION` (from step 2)
2224
- 8. Migrate your users from the previous version (`zapier migrate OLD_VERSION YOUR_NEW_VERSION`)
2225
-
2226
- <a id="analytics"></a>
2227
- ### What Analytics are Collected?
2228
-
2229
- Starting with v8.4.0, Zapier collects information about each invocation of the CLI tool.
2230
-
2231
- This data is collected purely to improve the CLI experience and will **never** be used for advertising or any non-product purpose. There are 3 collection modes that are set on a per-computer basis.
2232
-
2233
- **Anonymous**
2234
-
2235
- When you run a command with analytics in `anonymous` mode, the following data is sent to Zapier:
2236
-
2237
- * which command you ran
2238
- * if that command is a known command
2239
- * how many arguments you supplied (but not the contents of the arguments)
2240
- * which flags you used (but not their contents)
2241
- * the version of CLI that you're using
2242
-
2243
- **Enabled** (the default)
2244
-
2245
- When analytics are fully `enabled`, the above is sent, plus:
2246
-
2247
- * your operating system (the result of calling [`process.platform`](https://nodejs.org/api/process.html#process_process_platform))
2248
- * your Zapier user id
2249
-
2250
- **Disabled**
2251
-
2252
- Lastly, analytics can be `disabled` entirely, either by running `zapier analytics --mode disabled` or setting the `DISABLE_ZAPIER_ANALYTICS` environment variable to `1`.
2253
-
2254
- We take great care not to collect any information about your filesystem or anything otherwise secret. You can see exactly what's being collecting at runtime by prefixing any command with `DEBUG=zapier:analytics`.
2255
-
2256
- ### What's the Difference Between an "App" and an "Integration"?
2257
-
2258
- We're in the process of doing some renaming across our Zapier marketing terms. Eventually we'll use "integration" everywhere. Until then, know that these terms are interchangeable and describe the code that you write that connects your API to Zapier.
2259
-
2260
- ## Command Line Tab Completion
2261
-
2262
- Introduced in v9.1.0, the `zapier autocomplete` command shows instructions for generating command line autocomplete.
2263
-
2264
- Follow those instructions to enable completion for `zapier` commands and flags!
2265
-
2266
- ## The Zapier Platform Packages
2267
-
2268
- The Zapier Platform consists of 3 npm packages that are released simultaneously.
2269
-
2270
- - [`zapier-platform-cli`](https://github.com/zapier/zapier-platform/tree/main/packages/cli) is the code that powers the `zapier` command. You use it most commonly with the `test`, `scaffold`, and `push` commands. It's installed with `npm install -g zapier-platform-cli` and does not correspond to a particular app.
2271
- - [`zapier-platform-core`](https://github.com/zapier/zapier-platform/tree/main/packages/core) is what allows your app to interact with Zapier. It holds the `z` object and app tester code. Your app depends on a specific version of `zapier-platform-core` in the `package.json` file. It's installed via `npm install` along with the rest of your app's dependencies.
2272
- - [`zapier-platform-schema`](https://github.com/zapier/zapier-platform/tree/main/packages/schema) enforces app structure behind the scenes. It's a dependency of `core`, so it will be installed automatically.
2273
-
2274
- To learn more about the structure of the code (especially if you're interested in contributing), check out the `ARCHITECTURE.md` file(s).
2275
-
2276
- ### Updating These Packages
2277
-
2278
- The Zapier platform and its tools are under active development. While you don't need to install every release, we release new versions because they are better than the last. We do our best to adhere to [Semantic Versioning](https://semver.org/) wherein we won't break your code unless there's a `major` release. Otherwise, we're just fixing bugs (`patch`) and adding features (`minor`).
2279
-
2280
- Broadly speaking, all releases will continue to work indefinitely. While you never *have* to upgrade your app's `zapier-platform-core` dependency, we recommend keeping an eye on the [changelog](https://github.com/zapier/zapier-platform/blob/main/CHANGELOG.md) to see what new features and bug fixes are available.
2281
-
2282
- For more info about which Node versions are supported, see [the faq](#how-do-i-manually-set-the-nodejs-version-to-run-my-app-with).
2283
-
2284
- <!-- TODO: if we decouple releases, change this -->
2285
- The most recently released version of `cli` and `core` is **PACKAGE_VERSION**. You can see the versions you're working with by running `zapier -v`.
2286
-
2287
- To update `cli`, run `npm install -g zapier-platform-cli`.
2288
-
2289
- To update the version of `core` your app depends on, set the `zapier-platform-core` dependency in your `package.json` to a version listed [here](https://www.npmjs.com/package/zapier-platform-core?activeTab=versions) and reinstall your dependencies (either `yarn` or `npm install`).
2290
-
2291
- For maximum compatibility, keep the versions of `cli` and `core` in sync.
2292
-
2293
- ## Get Help!
2294
-
2295
- You can get help by either emailing `partners@zapier.com` or by [joining our developer community here](https://community.zapier.com/developer-discussion-13).
2296
-
2297
- ---
2298
-
2299
- ## Developing on the CLI
2300
-
2301
- See [CONTRIBUTING.md](https://github.com/zapier/zapier-platform/blob/main/CONTRIBUTING.md).