@lowdefy/docs-content 6.0.0 → 7.0.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.
Files changed (285) hide show
  1. package/README.md +1 -0
  2. package/content/actions/downloadcsv.md +1 -1
  3. package/content/actions/emailotpsend.md +58 -0
  4. package/content/actions/emailotpverify.md +79 -0
  5. package/content/actions/getlocalstorage.md +43 -0
  6. package/content/actions/link.md +47 -1
  7. package/content/actions/login.md +25 -5
  8. package/content/actions/logout.md +7 -5
  9. package/content/actions/magiclinkverify.md +117 -0
  10. package/content/actions/pdfmake.md +2 -2
  11. package/content/actions/posthogalias.md +29 -0
  12. package/content/actions/posthogcapture.md +49 -0
  13. package/content/actions/posthogcapturepageleave.md +38 -0
  14. package/content/actions/posthogfeatureflag.md +50 -0
  15. package/content/actions/posthoggroup.md +37 -0
  16. package/content/actions/posthogidentify.md +54 -0
  17. package/content/actions/posthoginit.md +96 -0
  18. package/content/actions/posthogoptin.md +29 -0
  19. package/content/actions/posthogoptout.md +29 -0
  20. package/content/actions/posthogpageview.md +37 -0
  21. package/content/actions/posthogreloadfeatureflags.md +47 -0
  22. package/content/actions/posthogreset.md +28 -0
  23. package/content/actions/posthogsetpersonproperties.md +36 -0
  24. package/content/actions/removelocalstorage.md +28 -0
  25. package/content/actions/resetvalidation.md +5 -3
  26. package/content/actions/setdarkmode.md +3 -3
  27. package/content/actions/setglobal.md +2 -0
  28. package/content/actions/setlocale.md +1 -1
  29. package/content/actions/setlocalstorage.md +34 -0
  30. package/content/actions/setstate.md +2 -0
  31. package/content/actions/validate.md +7 -4
  32. package/content/adapter-reference/mongodbauthadapter.md +46 -0
  33. package/content/agents/agent-endpoint-tools.md +24 -0
  34. package/content/agents/agent-properties.md +13 -3
  35. package/content/agents/agent-server-hooks.md +1 -1
  36. package/content/agents/agentchat.md +41 -4
  37. package/content/agents/agentconversations.md +42 -8
  38. package/content/agents/agents-introduction.md +107 -0
  39. package/content/callback-reference/auth0logoutcallback.md +54 -0
  40. package/content/concepts/ai-agent-docs.md +455 -106
  41. package/content/concepts/blocks.md +150 -0
  42. package/content/concepts/connections-and-requests.md +402 -0
  43. package/content/concepts/custom-html.md +42 -0
  44. package/content/concepts/custom-styling.md +50 -5
  45. package/content/concepts/dynamic-page-content.md +309 -0
  46. package/content/concepts/events-and-actions.md +185 -2
  47. package/content/concepts/four-primitives.md +31 -0
  48. package/content/concepts/html-attributes.md +293 -0
  49. package/content/concepts/i18n.md +12 -3
  50. package/content/concepts/keyboard-shortcuts.md +2 -2
  51. package/content/concepts/layout-overview.md +1 -1
  52. package/content/concepts/logger.md +99 -0
  53. package/content/concepts/lowdefy-api.md +1319 -0
  54. package/content/concepts/lowdefy-schema.md +144 -3
  55. package/content/concepts/menus.md +8 -7
  56. package/content/concepts/module-authoring.md +76 -5
  57. package/content/concepts/modules.md +3 -1
  58. package/content/concepts/notifications.md +180 -0
  59. package/content/concepts/operators.md +7 -0
  60. package/content/concepts/page-and-app-state.md +252 -0
  61. package/content/concepts/page-paths.md +209 -0
  62. package/content/concepts/theming.md +582 -0
  63. package/content/connections/aigateway.md +375 -0
  64. package/content/connections/anthropic.md +169 -2
  65. package/content/connections/awss3.md +178 -2
  66. package/content/connections/axioshttp.md +181 -0
  67. package/content/connections/google.md +169 -2
  68. package/content/connections/mongodb.md +1014 -3
  69. package/content/connections/openai-connection.md +169 -2
  70. package/content/connections/sendgridmail.md +3 -0
  71. package/content/connections/smtp.md +16 -0
  72. package/content/connections/treg.md +329 -0
  73. package/content/container-blocks/affix.md +47 -7
  74. package/content/container-blocks/alert.md +76 -24
  75. package/content/container-blocks/badge.md +100 -24
  76. package/content/container-blocks/box.md +9 -9
  77. package/content/container-blocks/card.md +132 -27
  78. package/content/container-blocks/carousel.md +60 -7
  79. package/content/container-blocks/collapse.md +153 -9
  80. package/content/container-blocks/configprovider.md +35 -13
  81. package/content/container-blocks/confirmmodal.md +69 -23
  82. package/content/container-blocks/content.md +62 -98
  83. package/content/container-blocks/descriptions.md +45 -4
  84. package/content/container-blocks/drawer.md +139 -28
  85. package/content/container-blocks/dropdownmenu.md +119 -31
  86. package/content/container-blocks/flex.md +40 -62
  87. package/content/container-blocks/footer.md +15 -11
  88. package/content/container-blocks/googlemapsheatmap.md +1 -1
  89. package/content/container-blocks/googlemapsscript.md +2 -2
  90. package/content/container-blocks/header.md +71 -36
  91. package/content/container-blocks/label.md +34 -7
  92. package/content/container-blocks/layout.md +52 -34
  93. package/content/container-blocks/masonry.md +17 -71
  94. package/content/container-blocks/mobilemenu.md +131 -88
  95. package/content/container-blocks/modal.md +161 -26
  96. package/content/container-blocks/pageheadermenu.md +138 -31
  97. package/content/container-blocks/pagesidebarlayout.md +230 -27
  98. package/content/container-blocks/pagesidermenu.md +153 -43
  99. package/content/container-blocks/popover.md +34 -31
  100. package/content/container-blocks/result.md +32 -21
  101. package/content/container-blocks/sider.md +85 -122
  102. package/content/container-blocks/span.md +7 -7
  103. package/content/container-blocks/spinner.md +3 -3
  104. package/content/container-blocks/splitter.md +150 -68
  105. package/content/container-blocks/tabs.md +64 -12
  106. package/content/container-blocks/tooltip.md +22 -46
  107. package/content/container-blocks/watermark.md +22 -4
  108. package/content/controls/parallel_for.md +21 -2
  109. package/content/controls/reject.md +26 -3
  110. package/content/controls/return.md +17 -1
  111. package/content/controls/throw.md +30 -2
  112. package/content/controls/try.md +24 -2
  113. package/content/controls/while.md +46 -0
  114. package/content/deployment/deployment-environments.md +146 -0
  115. package/content/deployment/docker.md +23 -7
  116. package/content/deployment/node-server.md +4 -0
  117. package/content/deployment/vercel.md +25 -19
  118. package/content/display-blocks/aggrid.md +33 -16
  119. package/content/display-blocks/anchor.md +16 -15
  120. package/content/display-blocks/avatar.md +57 -37
  121. package/content/display-blocks/breadcrumb.md +70 -21
  122. package/content/display-blocks/button.md +93 -19
  123. package/content/display-blocks/calendar.md +12 -0
  124. package/content/display-blocks/clickablehtml.md +239 -0
  125. package/content/display-blocks/dangeroushtml.md +1 -1
  126. package/content/display-blocks/difflist.md +1 -1
  127. package/content/display-blocks/difftimeline.md +1 -1
  128. package/content/display-blocks/divider.md +64 -3
  129. package/content/display-blocks/dropdownbutton.md +81 -30
  130. package/content/display-blocks/echart.md +35 -1
  131. package/content/display-blocks/eventlog.md +363 -0
  132. package/content/display-blocks/floatbutton.md +129 -42
  133. package/content/display-blocks/html.md +61 -1
  134. package/content/display-blocks/icon.md +250 -67
  135. package/content/display-blocks/img.md +2 -2
  136. package/content/display-blocks/menu.md +146 -73
  137. package/content/display-blocks/message.md +38 -124
  138. package/content/display-blocks/notification.md +94 -222
  139. package/content/display-blocks/paragraph.md +59 -9
  140. package/content/display-blocks/pollingtimer.md +263 -0
  141. package/content/display-blocks/progress.md +96 -17
  142. package/content/display-blocks/qrcode.md +19 -4
  143. package/content/display-blocks/s3download.md +1 -1
  144. package/content/display-blocks/search.md +19 -9
  145. package/content/display-blocks/skeletonbutton.md +1 -0
  146. package/content/display-blocks/skeletoninput.md +1 -0
  147. package/content/display-blocks/statistic.md +75 -17
  148. package/content/display-blocks/steps.md +58 -25
  149. package/content/display-blocks/table.md +2527 -0
  150. package/content/display-blocks/tablelight.md +621 -0
  151. package/content/display-blocks/tag.md +102 -17
  152. package/content/display-blocks/title.md +50 -11
  153. package/content/display-blocks/tour.md +33 -23
  154. package/content/input-blocks/autocomplete.md +81 -9
  155. package/content/input-blocks/buttonselector.md +45 -8
  156. package/content/input-blocks/captcha.md +40 -0
  157. package/content/input-blocks/checkboxselector.md +97 -7
  158. package/content/input-blocks/checkboxswitch.md +33 -3
  159. package/content/input-blocks/colorselector.md +63 -14
  160. package/content/input-blocks/daterangeselector.md +165 -45
  161. package/content/input-blocks/dateselector.md +139 -41
  162. package/content/input-blocks/datetimeselector.md +158 -49
  163. package/content/input-blocks/inputgallery.md +3 -3
  164. package/content/input-blocks/intentinput.md +207 -0
  165. package/content/input-blocks/monthselector.md +120 -52
  166. package/content/input-blocks/multipleselector.md +150 -39
  167. package/content/input-blocks/numberinput.md +98 -12
  168. package/content/input-blocks/pagination.md +70 -14
  169. package/content/input-blocks/paragraphinput.md +51 -37
  170. package/content/input-blocks/passwordinput.md +60 -6
  171. package/content/input-blocks/phonenumberinput.md +59 -26
  172. package/content/input-blocks/placesautocomplete.md +319 -0
  173. package/content/input-blocks/radioselector.md +83 -7
  174. package/content/input-blocks/ratingslider.md +57 -26
  175. package/content/input-blocks/s3uploadbutton.md +24 -24
  176. package/content/input-blocks/s3uploaddragger.md +3 -3
  177. package/content/input-blocks/s3uploadphoto.md +5 -5
  178. package/content/input-blocks/segmentedselector.md +72 -32
  179. package/content/input-blocks/selector.md +109 -21
  180. package/content/input-blocks/switch.md +65 -17
  181. package/content/input-blocks/tableinput.md +445 -0
  182. package/content/input-blocks/tagmultipleselector.md +114 -0
  183. package/content/input-blocks/tagselector.md +114 -0
  184. package/content/input-blocks/textarea.md +32 -3
  185. package/content/input-blocks/textinput.md +70 -29
  186. package/content/input-blocks/tiptapinput.md +1 -1
  187. package/content/input-blocks/tiptapmentioninput.md +2 -2
  188. package/content/input-blocks/titleinput.md +39 -12
  189. package/content/input-blocks/treeinput.md +49 -25
  190. package/content/input-blocks/treemultipleselector.md +127 -10
  191. package/content/input-blocks/treeselector.md +97 -9
  192. package/content/input-blocks/upload.md +64 -15
  193. package/content/input-blocks/uploaddragger.md +17 -1
  194. package/content/input-blocks/uploadphoto.md +18 -1
  195. package/content/input-blocks/weekselector.md +120 -55
  196. package/content/learn/introduction.md +27 -0
  197. package/content/learn/quickstart.md +53 -0
  198. package/content/learn/showcase.md +8 -0
  199. package/content/list-blocks/controlledlist.md +24 -15
  200. package/content/list-blocks/list.md +11 -11
  201. package/content/list-blocks/masonrylist.md +7 -34
  202. package/content/migration/auth-upgrade.md +337 -0
  203. package/content/migration/upgrade-guide.md +1 -0
  204. package/content/migration/v3-to-v4.md +417 -0
  205. package/content/migration/v6-to-v7.md +620 -0
  206. package/content/operators/_agent.md +155 -0
  207. package/content/operators/_app.md +2 -1
  208. package/content/operators/_array.md +122 -1
  209. package/content/operators/_build.md +1 -0
  210. package/content/operators/_credential.md +57 -0
  211. package/content/operators/_cron.md +292 -0
  212. package/content/operators/_date.md +2 -0
  213. package/content/operators/_error.md +196 -0
  214. package/content/operators/_get.md +6 -6
  215. package/content/operators/_hmac.md +78 -0
  216. package/content/operators/_js.md +2 -1
  217. package/content/operators/_location.md +1 -1
  218. package/content/operators/_media.md +13 -0
  219. package/content/operators/_module.md +56 -2
  220. package/content/operators/_operator.md +17 -3
  221. package/content/operators/_path_params.md +82 -0
  222. package/content/operators/_ref.md +258 -0
  223. package/content/operators/_request.md +1 -1
  224. package/content/operators/_request_details.md +6 -0
  225. package/content/operators/_type.md +14 -3
  226. package/content/operators/_url_query.md +2 -0
  227. package/content/operators/_user.md +3 -3
  228. package/content/plugins/plugins-actions.md +10 -0
  229. package/content/plugins/plugins-connections.md +25 -0
  230. package/content/plugins/plugins-dev.md +66 -0
  231. package/content/plugins/plugins-icon-sets.md +267 -0
  232. package/content/plugins/plugins-introduction.md +27 -1
  233. package/content/plugins/plugins.md +19 -0
  234. package/content/plugins/posthog.md +359 -0
  235. package/content/provider-reference/auth-js-providers.md +107 -0
  236. package/content/provider-reference/openidconnectprovider.md +44 -0
  237. package/content/recipes/recipes.md +16 -0
  238. package/content/reference/actions-reference.md +31 -0
  239. package/content/reference/blocks-reference.md +35 -0
  240. package/content/reference/cli.md +403 -0
  241. package/content/reference/connections-reference.md +23 -0
  242. package/content/reference/operators-reference.md +47 -0
  243. package/content/reference/reference.md +16 -0
  244. package/content/reference/schema-reference.md +12 -0
  245. package/content/testing/config-tests.md +677 -0
  246. package/content/testing/e2e-configuration.md +31 -1
  247. package/content/testing/e2e-getting-started.md +1 -1
  248. package/content/testing/e2e-introduction.md +1 -1
  249. package/content/testing/e2e-writing-tests.md +12 -1
  250. package/content/testing/explore-pull-request.md +136 -0
  251. package/content/testing/journey-data-sets.md +326 -0
  252. package/content/tutorial/tutorial-actions-operators.md +2 -2
  253. package/content/tutorial/tutorial-add-blocks.md +2 -2
  254. package/content/tutorial/tutorial-create-page.md +48 -2
  255. package/content/tutorial/tutorial-display-data-page.md +3 -3
  256. package/content/tutorial/tutorial-requests-api.md +155 -0
  257. package/content/tutorial/tutorial-requests-sql.md +153 -0
  258. package/content/tutorial/tutorial-start.md +66 -1
  259. package/content/user-authentication/auth-configuration.md +267 -0
  260. package/content/user-authentication/auth-providers.md +24 -0
  261. package/content/user-authentication/auth-steps.md +141 -0
  262. package/content/user-authentication/login-and-logout.md +160 -8
  263. package/content/user-authentication/mcp-oauth.md +424 -0
  264. package/content/user-authentication/organizations.md +246 -0
  265. package/content/user-authentication/protected-pages-apis.md +97 -0
  266. package/content/user-authentication/roles.md +49 -0
  267. package/content/user-authentication/two-factor.md +229 -0
  268. package/content/user-authentication/user-object.md +58 -0
  269. package/content/user-authentication/users-introduction.md +8 -0
  270. package/content/websockets/websocket-publish.md +105 -0
  271. package/content/websockets/websocket-subscriptions.md +136 -0
  272. package/content/websockets/websockets-introduction.md +101 -0
  273. package/hazards.json +56 -0
  274. package/index.json +3472 -14
  275. package/package.json +10 -1
  276. package/scripts/extractAgentDocs.js +41 -30
  277. package/scripts/hashDocSources.js +38 -0
  278. package/scripts/isRedirectPage.js +26 -0
  279. package/scripts/recordSourceHashes.js +97 -0
  280. package/scripts/resolvePageSections.js +42 -0
  281. package/scripts/sectionKind.js +27 -0
  282. package/content/concepts/cli.md +0 -223
  283. package/content/other/introduction.md +0 -39
  284. package/content/other/next-auth-providers.md +0 -3
  285. /package/content/{other → actions}/updatesession.md +0 -0
@@ -0,0 +1,1319 @@
1
+ # Lowdefy APIs
2
+
3
+ Lowdefy APIs allow you to create custom server-side API endpoints within your Lowdefy application. These endpoints can execute complex server-side logic, orchestrate multiple database or external API calls, perform data transformations, and implement business workflows that require server-side processing.
4
+
5
+ APIs are particularly useful when you need to:
6
+
7
+ - Coordinate multiple requests in a specific sequence.
8
+ - Implement complex business logic that should run on the server.
9
+ - Transform or aggregate data from multiple sources.
10
+ - Create reusable endpoints that can be called from multiple pages.
11
+ - Build webhook endpoints for external services.
12
+ - Keep sensitive operations and data on the server.
13
+
14
+ ## How Lowdefy APIs Work
15
+
16
+ Lowdefy APIs are defined at the root level of your configuration, similar to connections and pages. Each API endpoint consists of a `routine` i.e. a sequence of steps and control structures that define the execution flow. When an API endpoint is called from the client using the [`CallAPI`](/CallAPI) action, the routine executes on the server with access to connections, secrets, and server-side operators.
17
+
18
+ The API execution flow:
19
+
20
+ 1. Client calls the API endpoint using the [`CallAPI`](/CallAPI) action with an optional payload.
21
+ 2. Server checks authorization based on the auth configuration in `lowdefy.yaml`.
22
+ 3. The endpoint routine executes sequentially (or in parallel where specified).
23
+ 4. Each step can make requests to connections, transform data, or control flow.
24
+ 5. The endpoint returns a response to the client.
25
+
26
+ ## API Endpoint Definition
27
+
28
+ API endpoints are defined in the `api` array at the root of your Lowdefy configuration. Each endpoint should have an `id` that is unique among all API endpoints in the app. The `endpointId` is used by the [`CallAPI`](/CallAPI) action to specify which endpoint to execute.
29
+
30
+ The schema for a Lowdefy API is:
31
+
32
+ - `id: string`: **Required** - A unique identifier for the API endpoint.
33
+ - `type: string`: **Required** - Either `Api` (callable from client pages and other endpoints) or `InternalApi` (callable only from other endpoints, not from client pages).
34
+ - `routine: array/object`: **Required** - The routine to execute. **Operators are evaluated**.
35
+ - `async: boolean`: **Optional** - Respond with `{ accepted: true }` immediately and run the routine in the background. See [Async Endpoints](#async-endpoints).
36
+ - `payloadSchema: object`: **Optional** - A JSON Schema every payload sent to this endpoint must match. Declaring it turns validation on for every caller, and it is required before an endpoint can be exposed as an MCP or agent tool. See [Payload Schema](#payload-schema).
37
+ - `webhook: boolean`: **Optional** - Make this endpoint a third-party webhook receiver — it takes the HTTP request raw instead of the CallAPI envelope. See [Webhook Endpoints](#webhook-endpoints).
38
+ - `schedules: array | object`: **Optional** - Cron schedules that run the routine on a timer. See [Scheduled Endpoints](#scheduled-endpoints-cron). Each item is an object with a `cron` expression and an optional `payload` object. With `config.environments` declared, `schedules` can instead be an object keyed by environment name (plus an optional `default`), see [Schedules per environment](#schedules-per-environment).
39
+
40
+ ###### API definition example:
41
+
42
+ ```yaml
43
+ lowdefy: '6.1.0'
44
+
45
+ connections:
46
+ - id: users
47
+ type: MongoDBCollection
48
+ properties:
49
+ collection: users
50
+ databaseUri:
51
+ _secret: MONGODB_URI
52
+
53
+ api:
54
+ - id: get_user_data
55
+ type: Api
56
+ routine:
57
+ - id: fetch_user
58
+ type: MongoDBFindOne
59
+ connectionId: users
60
+ properties:
61
+ query:
62
+ user_id:
63
+ _payload: user_id
64
+ - :return:
65
+ _step: fetch_user
66
+
67
+ pages:
68
+ # ... your pages
69
+ ```
70
+
71
+ ## Authentication and Authorization
72
+
73
+ Lowdefy APIs use the same [authorization configuration](/protected-pages-apis) as pages. By default, API endpoints are public (accessible without authentication), just like pages. Authorization is configured in the `auth.api` section of the `lowdefy.yaml` file.
74
+
75
+ Unlike requests which are defined on a specific page and inherit the authorization of the page they are defined on, API endpoints can be called from any page in the app. Thus they do not inherit the authorization of the page they are called from, and authorization should be configured separately.
76
+
77
+ ```yaml
78
+ lowdefy: '6.1.0'
79
+
80
+ auth:
81
+ # Configure which APIs require authentication
82
+ api:
83
+ protected: true
84
+ public:
85
+ - health_check
86
+ roles:
87
+ admin:
88
+ - admin_api
89
+ - manage_users
90
+ manager:
91
+ - manager_reports
92
+ - team_data
93
+
94
+ api:
95
+ # Your API definitions
96
+ # ...
97
+ ```
98
+
99
+ ## Scheduled Endpoints (Cron)
100
+
101
+ An endpoint can declare `schedules` to run its routine on a timer instead of (or in addition to) being called from the client. This is currently supported on [Vercel deployments](/vercel), where each schedule becomes a native Vercel cron job.
102
+
103
+ ```yaml
104
+ api:
105
+ - id: purge_stale_conversations
106
+ type: Api
107
+ schedules:
108
+ - cron: '0 6 * * *'
109
+ payload: { mode: full }
110
+ - cron: '*/15 * * * *'
111
+ payload: { mode: incremental }
112
+ routine:
113
+ - id: purge
114
+ type: MongoDBDeleteMany
115
+ connectionId: conversations
116
+ properties:
117
+ filter:
118
+ updatedAt:
119
+ $lt:
120
+ _payload: cutoff
121
+ ```
122
+
123
+ Each schedule item has:
124
+
125
+ - `cron: string`: **Required** - A 5-field cron expression (`minute hour day-of-month month day-of-week`), evaluated in **UTC**. Named values like `MON`/`JAN` are not supported, and day-of-month and day-of-week are mutually exclusive (one must be `*`). Cron expressions must be unique within an endpoint.
126
+ - `payload: object`: **Optional** - The payload passed to the routine for this schedule, available via the `_payload` operator. Different schedules can pass different payloads to the same routine.
127
+
128
+ When a schedule fires, the routine runs as a **system context**: there is no authenticated user, so `_user` is `undefined`. The routine still has full access to connections, requests, operators and secrets — write scheduled routines so they do not depend on a logged-in user. Because cron delivery is best-effort and not retried, design scheduled routines to be idempotent.
129
+
130
+ To test a scheduled routine locally, run it as a system context with the dev server's `lowdefy_run_endpoint` MCP tool (or `POST /lowdefy-docs/run-endpoint`) with `system: true` — see [Docs for AI Agents](/ai-agent-docs#running-endpoints).
131
+
132
+ See [Deploy with Vercel](/vercel) for how schedules become cron jobs, how to secure them with `CRON_SECRET`, and the applicable plan limits.
133
+
134
+ ### Schedules per environment
135
+
136
+ Vercel fires cron jobs only on the **production** deployment, so a staging or develop deployment never runs its schedules on its own. Declare your deployment environments once under [`config.environments`](/deployment-environments) and set `LOWDEFY_ENVIRONMENT` on each deployment. Every environment with a `cron.secret` has its schedules registered on production too; when one fires, production pings that environment's own `/api/cron/<endpointId>` at its `url` (fire-and-forget) so the environment runs its own code. `cron.secret` is the **name** of a Lowdefy secret, a plain string — not a `_secret` operator.
137
+
138
+ ```yaml
139
+ config:
140
+ environments:
141
+ prod:
142
+ url: https://example.com # Vercel fires crons here
143
+ staging:
144
+ url: https://staging.example.com
145
+ cron:
146
+ secret: STAGING_CRON_SECRET # Lowdefy secret holding staging's CRON_SECRET
147
+ develop:
148
+ url: https://develop.example.com
149
+ cron:
150
+ secret: DEVELOP_CRON_SECRET
151
+ enabled: false # register no crons for develop
152
+ ```
153
+
154
+ With environments declared, `schedules` can be keyed by environment name. A `default` list applies to every environment that has no entry of its own, and an empty list turns the crons off for that environment:
155
+
156
+ ```yaml
157
+ api:
158
+ - id: purge_stale_conversations
159
+ type: Api
160
+ schedules:
161
+ default:
162
+ - cron: '*/15 * * * *'
163
+ staging:
164
+ - cron: '0 * * * *' # hourly on staging
165
+ develop: [] # off on develop
166
+ routine: []
167
+ ```
168
+
169
+ A plain array still works and applies to every environment. Environment names in `schedules` must be declared in `config.environments` (`default` is reserved). A build with no current environment runs the `default` schedules. This shape also works through module vars: a module endpoint with `schedules: { _module.var: tick_schedule }` needs no change — the app sets `tick_schedule: { default: [...], staging: [...] }` in its module vars (a module var that pins `type: array` for its schedule var must drop the pin to accept the keyed form).
170
+
171
+ The production deployment needs one secret per forwarded environment: the environment variable `LOWDEFY_SECRET_<secret name>` (for example `LOWDEFY_SECRET_STAGING_CRON_SECRET`) set to that environment's `CRON_SECRET`. Forwarded requests carry the firing cron in `x-vercel-cron-schedule` and the environment name in `x-lowdefy-cron-environment`; the target resolves its own schedules from those. See [Deployment environments](/deployment-environments) for the other environment settings and [Deploy with Vercel](/vercel) for the routes involved.
172
+
173
+ ## Payload Schema
174
+
175
+ An endpoint can declare a `payloadSchema` — a [JSON Schema](https://json-schema.org/) describing the payload it accepts. A declared schema is a contract, not documentation: **every** payload is validated against it before the routine starts, whatever the caller is — the [`CallAPI`](/CallAPI) action from a page, an MCP `tools/call`, an [agent tool call](/ai-agent-docs), a nested `CallApi` from another endpoint (including a [detached](#detached-endpoint-calls) one), or a scheduled run's `schedule.payload`. Every `_payload` read in the routine can then rely on the shape.
176
+
177
+ ```yaml
178
+ api:
179
+ - id: create_order
180
+ type: Api
181
+ payloadSchema:
182
+ type: object
183
+ required: [sku, quantity]
184
+ properties:
185
+ sku: { type: string }
186
+ quantity: { type: number, minimum: 1 }
187
+ routine:
188
+ - id: insert
189
+ type: MongoDBInsertOne
190
+ connectionId: orders
191
+ properties:
192
+ doc:
193
+ sku:
194
+ _payload: sku
195
+ quantity:
196
+ _payload: quantity
197
+ ```
198
+
199
+ A payload that does not match is refused before the routine runs, with a message naming the endpoint, the failing location and the reason, for example:
200
+
201
+ ```
202
+ Payload for endpoint "create_order" does not match its payloadSchema at /quantity: must be number.
203
+ ```
204
+
205
+ The reason says what would be accepted where the schema says it: an `enum` miss lists the allowed values, an `additionalProperties: false` miss names the unexpected properties, and a `pattern` miss quotes the pattern. When a location fails both its `type` and one of `enum`, `pattern`, `required` or `additionalProperties`, that keyword is reported. Further failures are counted at the end, e.g. `(and 2 more)`.
206
+
207
+ ```
208
+ Payload for endpoint "create_order" does not match its payloadSchema at /status: must be equal to one of the allowed values (draft, placed).
209
+ Payload for endpoint "create_order" does not match its payloadSchema at (root): must NOT have additional properties (colour).
210
+ ```
211
+
212
+ Who built the payload decides what kind of error the refusal is.
213
+
214
+ - **An outside caller** sent it: an API client calling `POST /api/endpoints/<endpointId>` without naming a page, an MCP tool call, or an agent tool call (the model wrote the arguments). The refusal is the caller's mistake, not a fault: a `UserError`, logged at warn level only and never reported as a server error.
215
+ - The REST call answers `400` with `{ name: 'UserError', message }`.
216
+ - The MCP tool call answers `isError: true` carrying the same message, so the model can correct the arguments and retry.
217
+ - The agent tool call surfaces the message to the model as a tool error.
218
+ - **The app's own config** built it: a page's [`CallAPI`](/CallAPI) action, a nested `CallApi` step (including a [detached](#detached-endpoint-calls) one), a Dynamic block's endpoint, an auth or agent hook, or a scheduled run's `schedule.payload`. The config breaks its own endpoint's contract, so the refusal is a `ConfigError`: logged as a server error with its config location, and a journey that triggers it fails.
219
+ - A page's `CallAPI` fails with the `ConfigError`; its `catch` actions see `_error.name` as `ConfigError`, and outside development the message is the generic server error message.
220
+ - A nested `CallApi` step fails its routine, a detached target fails its run, and a scheduled run fails, each with the message in the logs.
221
+
222
+ There is **no opt-out** — no `validate: false`, no strict mode, no per-caller exemption. If you do not want a payload validated, do not declare a `payloadSchema`. The schema cannot be combined with `webhook`: a webhook routine receives the raw `{ body, query, headers }` transport envelope, never the `payloadSchema` shape, so declaring both is a build error. Validate a webhook body with a [`ValidateSchema` step](#validating-data-as-a-routine-step) instead.
223
+
224
+ ## Async Endpoints
225
+
226
+ An endpoint with `async: true` responds with `{ accepted: true }` immediately and runs its routine in the background. The caller does not wait for the routine to finish — the same way `async: true` [actions](/events-and-actions) do not block the rest of an action chain.
227
+
228
+ ```yaml
229
+ api:
230
+ - id: rebuild_search_index
231
+ type: Api
232
+ async: true
233
+ routine:
234
+ # long-running work ...
235
+ ```
236
+
237
+ - Authorization is checked **before** the call is accepted — an unauthorized caller gets an error, not `{ accepted: true }`.
238
+ - The routine's result never reaches the caller. Completion or failure is written to the server logs; anything else the caller needs to see must be written by the routine itself (for example a status document in a database).
239
+ - `async: true` also applies to scheduled runs — the cron trigger is acknowledged immediately and the routine runs in the background.
240
+ - On serverless deployments the background work still runs inside the same function invocation, so it remains bounded by the function's `maxDuration` — see [Deploy with Vercel](/vercel). To run work in a separate invocation with a fresh time budget, use a [detached endpoint call](#detached-endpoint-calls).
241
+
242
+ ## Webhook Endpoints
243
+
244
+ An endpoint with `webhook: true` is a receiver for third-party webhooks (AWS SNS, Azure Event Grid, Stripe, GitHub, ...). It is served on the same `POST /api/endpoints/<endpointId>` URL as every other endpoint, but the request is handled raw:
245
+
246
+ - The routine's `payload` is `{ body, query, headers }` — the caller's own body format (parsed as JSON when possible, the raw string otherwise; content-type is ignored since services like SNS post JSON as `text/plain`), plus the URL query parameters and request headers.
247
+ - The routine's `:return` value is sent back **verbatim** as the response body — webhook handshakes like Event Grid's `{ validationResponse }` require exact response shapes, so no `{ error, response, status }` envelope is applied.
248
+ - The routine has no user session (`_user` resolves to undefined), and the endpoint's `auth` config is not applied. It runs untrusted, so it can only `CallApi` public endpoints, until a [`webhook.verify`](#verifying-the-sender) request passes. Without a verifier, **authenticating the caller is the routine's own first step**, typically a shared-secret query parameter (`?t=<token>`) compared against a stored value, or a signature header. Because the session check never applies, a webhook endpoint must resolve to public under `auth.api` — the build fails if it is protected by `auth.api.protected` or roles; list it in `auth.api.public` (or remove the flag) to make the intent explicit.
249
+
250
+ ```yaml
251
+ id: stripe-webhook
252
+ type: Api
253
+ webhook: true
254
+ routine:
255
+ - :if:
256
+ _ne:
257
+ - _payload: query.t
258
+ - _secret: STRIPE_WEBHOOK_TOKEN
259
+ :then:
260
+ - :return:
261
+ error: unauthorized
262
+ - id: handle_event
263
+ type: MongoDBInsertOne
264
+ connectionId: stripe_events
265
+ properties:
266
+ doc:
267
+ _payload: body
268
+ - :return:
269
+ received: true
270
+ ```
271
+
272
+ :::warning
273
+ A `webhook: true` endpoint is publicly reachable by design — never declare it on an endpoint that does not authenticate its caller inside the routine.
274
+ :::
275
+
276
+ ### Verifying the sender
277
+
278
+ Set `webhook` to `{ verify: <request> }` to check the sender before the routine runs. The verifier is a request (`connectionId`, `type`, `properties`) run against the incoming request. When it returns `true` or `{ verified: true }`, the routine runs as a trusted system context, so it can `CallApi` protected endpoints. When it returns anything else or throws, the endpoint answers `401` and the routine never runs. A verifier whose own service can not be reached (it throws a `ServiceError`) fails the request with an error instead, so an outage is never reported as a forged webhook. A `webhook: true` endpoint with no verifier runs untrusted throughout.
279
+
280
+ The verifier's `_payload` is `{ body, rawBody, query, headers }`:
281
+
282
+ - `body`: the parsed body, as the routine sees it.
283
+ - `rawBody`: the request body exactly as received, as a string. Senders such as GitHub (`X-Hub-Signature-256`), Stripe (`Stripe-Signature`) and Slack (`X-Slack-Signature`) sign the exact bytes they post, and serialising the parsed `body` again does not reproduce them (key order, whitespace and unicode escapes differ), so a signature check must use `rawBody`. A body that is not JSON arrives as `rawBody` too, so the verifier can refuse it.
284
+ - `query` and `headers`: the URL query parameters and the request headers (lower-case names).
285
+
286
+ `rawBody` is given only to the verifier. The routine's payload stays `{ body, query, headers }`.
287
+
288
+ A signature check is usually a small request in a project plugin. This one checks GitHub's `X-Hub-Signature-256`, an HMAC-SHA256 of the body with the webhook secret:
289
+
290
+ ```js
291
+ import crypto from 'crypto';
292
+
293
+ function GitHubSignature({ request }) {
294
+ const expected = `sha256=${crypto
295
+ .createHmac('sha256', request.secret)
296
+ .update(request.rawBody, 'utf8')
297
+ .digest('hex')}`;
298
+ const received = request.signature ?? '';
299
+ if (expected.length !== received.length) {
300
+ return false;
301
+ }
302
+ return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received));
303
+ }
304
+
305
+ GitHubSignature.schema = {};
306
+ GitHubSignature.meta = { checkRead: false, checkWrite: false };
307
+
308
+ export default GitHubSignature;
309
+ ```
310
+
311
+ ```yaml
312
+ id: github-webhook
313
+ type: Api
314
+ webhook:
315
+ verify:
316
+ connectionId: github_signature
317
+ type: GitHubSignature
318
+ properties:
319
+ rawBody:
320
+ _payload: rawBody
321
+ signature:
322
+ _payload: headers.x-hub-signature-256
323
+ secret:
324
+ _secret: GITHUB_WEBHOOK_SECRET
325
+ routine:
326
+ - id: save_event
327
+ type: MongoDBInsertOne
328
+ connectionId: github_events
329
+ properties:
330
+ doc:
331
+ event:
332
+ _payload: headers.x-github-event
333
+ body:
334
+ _payload: body
335
+ - :return:
336
+ received: true
337
+ ```
338
+
339
+ ### Answering with a status
340
+
341
+ A webhook endpoint answers with an HTTP status that says how the run ended, so the sender can tell its own mistake from an outage:
342
+
343
+ | Outcome | Status | Body |
344
+ | --- | --- | --- |
345
+ | The routine finished | `200` | Its `:return` value, or `{ "ok": true }` when it returned nothing |
346
+ | A [`:return`](/:return) with `:content_type: text/plain` | `200` | The returned string as plain text (see [Answering with plain text](#answering-with-plain-text)) |
347
+ | A [`:reject`](/:reject) with `:status` | That status (400 to 499) | `:body` as given, or the error body below |
348
+ | A [`:reject`](/:reject) without `:status` | `400` | `{ "error": { "code": "rejected", "message": <the reject message> } }`, or `:body` when given |
349
+ | A failed [`ValidateSchema` step](#validating-data-as-a-routine-step) (with `throwOnInvalid` on) | `400` | `{ "error": { "code": "invalid_request", "message": <names the failing path> } }` |
350
+ | The `verify` request did not pass | `401` | `{ "error": { "code": "unauthorized", "message": "Webhook verification failed." } }` |
351
+ | Any other uncaught error | `500` | `{ "error": { "code": "internal_error", "message": "Webhook failed." } }`, with nothing from the error itself |
352
+
353
+ A `:reject` or a failed `ValidateSchema` step in an endpoint the routine calls with `CallApi` sets the answer the same way, so the work can live in an `InternalApi` endpoint the webhook calls. `:status` and `:body` are accepted only on a `:reject` in a webhook endpoint or an `InternalApi` endpoint; on any other endpoint they are a build error. An error a `:catch` handles does not change the answer. A `:reject` is never caught, so it always sets it.
354
+
355
+ ```yaml
356
+ id: support-tickets
357
+ type: Api
358
+ webhook:
359
+ verify:
360
+ _ref: support/verify_signature.yaml
361
+ routine:
362
+ - id: check_body
363
+ type: ValidateSchema
364
+ properties:
365
+ schema:
366
+ _ref: support/ticket_schema.json
367
+ data:
368
+ _payload: body
369
+ - id: find_ticket
370
+ type: MongoDBFindOne
371
+ connectionId: tickets
372
+ properties:
373
+ query:
374
+ _id:
375
+ _payload: body.ticket_id
376
+ - :if:
377
+ _eq:
378
+ - _step: find_ticket
379
+ - null
380
+ :then:
381
+ :reject: Ticket not found.
382
+ :status: 404
383
+ :body:
384
+ error:
385
+ code: not_found
386
+ ticket_id:
387
+ _payload: body.ticket_id
388
+ - :return:
389
+ ticket:
390
+ _step: find_ticket
391
+ ```
392
+
393
+ ### Answering with plain text
394
+
395
+ Some senders check a new subscription with a handshake that wants a plain-text reply. Microsoft Graph, for one, posts to the notification URL with `?validationToken=<token>` and expects a `200` whose body is exactly the token, with `Content-Type: text/plain`, within 10 seconds. Set `:content_type: text/plain` on the [`:return`](/:return) that answers it: the endpoint answers `200` with the returned string as the body, `Content-Type: text/plain; charset=UTF-8` and `X-Content-Type-Options: nosniff`.
396
+
397
+ ```yaml
398
+ id: graph-notifications
399
+ type: Api
400
+ webhook: true
401
+ routine:
402
+ - :if:
403
+ _ne:
404
+ - _payload: query.validationToken
405
+ - null
406
+ :then:
407
+ :return:
408
+ _payload: query.validationToken
409
+ :content_type: text/plain
410
+ # A change notification: check its clientState, then handle body.value.
411
+ - :return:
412
+ received: true
413
+ ```
414
+
415
+ `text/plain` is the only content type, and the returned value must be a string; any other value fails the run with the `500` answer above. `:content_type` is accepted only on a `:return` in a webhook endpoint, since the `:return` of an endpoint the webhook calls with `CallApi` is a step result, not the answer. Anywhere else it is a build error. A `:return` without `:content_type` answers JSON as before.
416
+
417
+ Endpoints without the flag are completely unaffected — the standard CallAPI envelope, auth config, and response shape apply exactly as before.
418
+
419
+ ## Routines
420
+
421
+ Routines define the execution logic of your API endpoint. Routines are defined as a nested combination of routines (subroutines). A routine can be one of:
422
+
423
+ - **Request**: A Lowdefy request definition.
424
+ - **Control**: A control structure, which often contain nested subroutines.
425
+ - **Array of Subroutines**: An array of subroutines to execute sequentially.
426
+
427
+ ### Requests
428
+
429
+ [Requests and connections](/connections-and-requests) can be used in API endpoints. Requests use the same connections defined in the `connections` section of the `lowdefy.yaml` file.
430
+
431
+ The `payload` property should not be defined for requests used in an API endpoint, the payload is specified by the [CallAPI](/CallAPI) action.
432
+
433
+ A single request definition is a valid routine definition.
434
+
435
+ ```yaml
436
+ id: log_message
437
+ type: Api
438
+ routine:
439
+ id: insert_log_message
440
+ type: MongoDBInsertOne
441
+ connectionId: logs
442
+ properties:
443
+ message:
444
+ _payload: message
445
+ doc:
446
+ timestamp:
447
+ _date: now
448
+ ```
449
+
450
+ ### Arrays of Subroutines
451
+
452
+ Subroutines in an array execute one after another:
453
+
454
+ ```yaml
455
+ id: my_endpoint
456
+ type: Api
457
+ routine:
458
+ - id: step_1
459
+ type: MongoDBFindOne
460
+ connectionId: users
461
+ properties:
462
+ query:
463
+ _id:
464
+ _payload: user_id
465
+
466
+ - id: step_2
467
+ type: MongoDBInsertOne
468
+ connectionId: audit-log
469
+ properties:
470
+ doc:
471
+ user_id:
472
+ _step: step_1._id
473
+ action: 'user_viewed'
474
+ timestamp:
475
+ _date: now
476
+
477
+ - :return:
478
+ user:
479
+ _step: step_1
480
+ logged: true
481
+ ```
482
+
483
+ Arrays can also be nested. This is useful when referencing shared subroutines that might be an array
484
+
485
+ ```yaml
486
+ # my_endpoint.yaml
487
+ id: my_endpoint
488
+ type: Api
489
+ routine:
490
+ - _ref: shared_routine.yaml
491
+ - :return:
492
+ user:
493
+ _step: step_1
494
+ logged: true
495
+ ```
496
+
497
+ ```yaml
498
+ # shared_routine.yaml
499
+ - id: step_1
500
+ type: MongoDBFindOne
501
+ connectionId: users
502
+ properties:
503
+ query:
504
+ _id:
505
+ _payload: user_id
506
+
507
+ - id: step_2
508
+ type: MongoDBInsertOne
509
+ connectionId: audit-log
510
+ properties:
511
+ doc:
512
+ user_id:
513
+ _step: step_1._id
514
+ action: 'user_viewed'
515
+ timestamp:
516
+ _date: now
517
+ ```
518
+
519
+ ### Control Structures
520
+
521
+ Control structures allow you to implement complex logic flows within your API routines. The following controls can be used in API routines:
522
+
523
+ - [`:for`](/for) - Iterate over an array sequentially.
524
+ - [`:if`](/if) - Execute different routines based on a condition.
525
+ - [`:log`](/log) - Output messages to the server console.
526
+ - [`:parallel`](/parallel) - Execute multiple routines simultaneously.
527
+ - [`:parallel_for`](/parallel_for) - Iterate over an array with concurrent processing.
528
+ - [`:reject`](/reject) - Return a user-facing error response. Not caught by [`:try`](/try)/`:catch` — it flows past every enclosing `:catch`, though `:finally` still runs.
529
+ - [`:return`](/return) - Return a successful response with data.
530
+ - [`:set_state`](/set_state) - Set values in server-side state.
531
+ - [`:switch`](/switch) - Handle multiple conditions with different outcomes.
532
+ - [`:throw`](/throw) - Throw a system error that can be caught.
533
+ - [`:try`](/try) - Handle errors with catch and finally blocks.
534
+
535
+ ## Calling Other Endpoints
536
+
537
+ API endpoints can call other endpoints server-side using `CallApi` steps. This enables you to compose complex workflows from smaller, reusable endpoints without HTTP overhead.
538
+
539
+ A `CallApi` step has:
540
+
541
+ - `id: string`: **Required** - A unique step id within the routine.
542
+ - `type: CallApi`: **Required** - Identifies this as an endpoint call step.
543
+ - `properties.endpointId: string`: **Required** - The id of the target endpoint. **Operators are evaluated**.
544
+ - `properties.payload: object`: Optional payload to pass to the target endpoint. **Operators are evaluated**.
545
+ - `properties.detached: boolean`: Optional - Fire-and-forget: dispatch the call and continue immediately, running the target in a separate server invocation. See [Detached Endpoint Calls](#detached-endpoint-calls).
546
+ - `properties.organization: string`: Optional - Run the target bound to this organization id, so the [tenant wall](/organizations#the-tenant-wall) filters and stamps its requests with it. Accepted only in a trusted system run. See [Running in One Organization](#running-in-one-organization). **Operators are evaluated**.
547
+ - `properties.caller: { id: string, name: string }`: Optional, only with `organization` - A named stand-in caller the target sees as `_user`. **Operators are evaluated**.
548
+
549
+ The called endpoint runs in an isolated context — it has its own `_step` results and `_payload`. Its internal step results do not appear in the calling endpoint's `_step` namespace. Only the value returned by the called endpoint's `:return` is stored as the step result.
550
+
551
+ ```yaml
552
+ api:
553
+ - id: process_order
554
+ type: Api
555
+ routine:
556
+ - id: validate
557
+ type: MongoDBFindOne
558
+ connectionId: orders
559
+ properties:
560
+ query:
561
+ _id:
562
+ _payload: order_id
563
+
564
+ - id: send_notification
565
+ type: CallApi
566
+ properties:
567
+ endpointId: send_email
568
+ payload:
569
+ to:
570
+ _step: validate.customer_email
571
+ subject: 'Order received'
572
+
573
+ - :return:
574
+ order:
575
+ _step: validate
576
+ email_sent:
577
+ _step: send_notification # Contains the :return value from send_email
578
+
579
+ - id: send_email
580
+ type: Api
581
+ routine:
582
+ - id: send
583
+ type: SendGridMail
584
+ connectionId: email
585
+ properties:
586
+ to:
587
+ _payload: to
588
+ subject:
589
+ _payload: subject
590
+ - :return:
591
+ success: true
592
+ ```
593
+
594
+ Endpoint calls can be nested up to 10 levels deep. Exceeding this limit throws an error — this prevents accidental infinite recursion.
595
+
596
+ Connection plugin resolvers can also invoke endpoints from inside their JS code using the `callApi` function on the resolver argument bag. The semantics — depth cap, isolated routine context, caller's user identity, `InternalApi` reachable — match the `CallApi` step. See [Connection and Request Plugins](/plugins-connections) for the resolver-side API.
597
+
598
+ ### Running in One Organization
599
+
600
+ Under the `tenant` organizations policy every walled request needs a caller organization. A scheduled run, an auth hook or a verified webhook has no caller, so a walled request in it fails closed. To do work for one organization from such a run, call the endpoint that does it with `organization`:
601
+
602
+ ```yaml
603
+ - id: process_installation
604
+ type: CallApi
605
+ properties:
606
+ endpointId: process_github_event
607
+ organization:
608
+ _step: installation.organization_id
609
+ caller:
610
+ id: github
611
+ name: GitHub
612
+ payload:
613
+ event:
614
+ _payload: body
615
+ ```
616
+
617
+ - The target runs as a system run bound to that organization. Every walled request inside it, and inside endpoints it calls in turn, is filtered and stamped with the organization, as for a signed-in member.
618
+ - `_user` inside the target is the stand-in caller when `caller` is named: `{ id, name, organization_id, system: true }`, with the bound organization and no roles. `system: true` is how config tells it from a signed-in member; no other caller carries it (a JWT strategy can not map a claim to `system`, and a dev mock user can not set it). Change logs whose `meta` reads `_user` record it as the user. Without `caller`, `_user` is null.
619
+ - `organization` and `caller` are accepted only in a trusted system run: a scheduled run, an auth hook, a webhook whose `verify` request passed (see [Webhook Endpoints](#webhook-endpoints)), or a detached run dispatched from one. The same step in a signed-in caller's routine, a strategy (API key) caller's, or a webhook with no passing verifier is refused, because the bound run is trusted as the system.
620
+ - A run that is already bound may restate its organization (and caller), but not name another.
621
+ - A `caller` without `organization`, or a static value of the wrong shape, is a build error.
622
+ - `detached: true` carries the binding: the detached run is bound to the same organization and caller.
623
+
624
+ Read the organization id from a row the routine already trusts (an installation record found by the verified webhook's payload, a schedule's list of organizations), never straight from an unverified request.
625
+
626
+ ### Detached Endpoint Calls
627
+
628
+ A `CallApi` step with `detached: true` does not wait for — or ever see — the target's result. The step dispatches the call and immediately continues, storing `{ detached: true, endpointId }` as its step result. The target runs as a new HTTP request to the deployment itself, which matters on serverless hosts: it executes in its **own** function invocation with a fresh `maxDuration` budget, so chained detached calls can process work that outlives any single invocation, without needing a queue.
629
+
630
+ ```yaml
631
+ - id: spawn_worker
632
+ type: CallApi
633
+ properties:
634
+ endpointId: process_batch
635
+ detached: true
636
+ payload:
637
+ batch_id:
638
+ _step: create_batch._id
639
+ ```
640
+
641
+ Detached calls differ from normal `CallApi` steps in important ways:
642
+
643
+ - **Same identity**: the target runs as whoever dispatched it — the user who called the parent endpoint, or a system context when the parent was a scheduled run, hook or verified webhook (bound to the same organization and stand-in caller when the call names [`organization`](#running-in-one-organization)). The target and its nested calls are authorized against that identity exactly as a synchronous `CallApi` would be, so a detached call reaches nothing the caller could not call directly. `InternalApi` endpoints are callable.
644
+ - **At-most-once, no retry**: if the dispatch or the target fails, nothing retries it. Design targets to be idempotent. The target's outcome exists only in the server logs and whatever its routine writes.
645
+ - **Accepted, then run**: the `/api/detached` route answers `202` as soon as the `CRON_SECRET` check passes, and runs the target after the response under the platform's `waitUntil` (bounded by the target's own `maxDuration`). The dispatching invocation's request settles at once instead of staying in flight (and holding its instance's memory) while the target runs, so a chain of detached calls is a chain of separate invocations, not nested in-flight requests. The outcome is logged as `detached_run_done` (with the routine's status) or `detached_run_failed`, which includes a target whose `auth` refuses the caller.
646
+ - **Requires `CRON_SECRET`**: the dispatch authenticates against the deployment's own `/api/detached` route with the `CRON_SECRET` environment variable (the same secret that secures cron, fail closed). The step fails with a config error if it is not set.
647
+ - **No depth cap across detached calls**: each detached target starts at call depth 0, so the 10-level nesting limit does not protect against detached recursion. An endpoint that (directly or indirectly) detaches back into itself will loop forever — spawning a new invocation each time.
648
+
649
+ ## Running Agents As A Routine Step
650
+
651
+ Routines can run an [agent](/agents-introduction) to completion using `CallAgent` steps. The agent runs headlessly — no chat UI, no streaming — looping through its tools until it finishes, and the result is stored as the step result. This lets endpoints delegate open-ended, multi-step work to an agent, while the surrounding routine stays explicit. For a single model call without tools, prefer the one-shot `GenerateText` / `GenerateObject` [request types](/Anthropic) — they are cheaper and more predictable.
652
+
653
+ A `CallAgent` step has:
654
+
655
+ - `id: string`: **Required** - A unique step id within the routine.
656
+ - `type: CallAgent`: **Required** - Identifies this as an agent call step.
657
+ - `properties.agentId: string`: **Required** - The id of the agent to run. **Operators are evaluated**.
658
+ - `properties.prompt: string`: **Required** - The task prompt for the agent run. **Operators are evaluated**.
659
+ - `properties.files: object[]`: Images and documents the model reads beside the prompt. Each entry is `{ url, mediaType }`: `url` is a link the model provider can fetch (a presigned link to a private file), and `mediaType` its type, like `image/png` or `application/pdf`. An `image/*` file is sent as an image, anything else as a document. The prompt and the files go to the model as one user message. A provider that takes that media type as a link fetches it itself (the main providers do for images and PDFs); for any other media type the server downloads the file first and sends its content. The server downloads only an `https:` link to a public address, checked on every redirect, within the agent's `fileDownload` limits (20 MB and 30 seconds by default). Either way the link must still be valid when the step runs. Which media types a model reads depends on the provider. **Operators are evaluated**.
660
+
661
+ The step result contains:
662
+
663
+ - `text: string`: The agent's final text output.
664
+ - `finishReason: string`: Why the run ended (`stop`, `length`, `tool-calls`, ...).
665
+ - `usage: object`: Accumulated token usage across all steps (`{ inputTokens, outputTokens, totalTokens, reasoningTokens, cacheReadTokens, cacheWriteTokens }`).
666
+ - `toolCalls: object[]`: The tool calls the agent made (`{ toolCallId, toolName, input }`).
667
+ - `toolResults: object[]`: The corresponding tool results (`{ toolCallId, toolName, output }`).
668
+
669
+ ```yaml
670
+ agents:
671
+ - id: research_agent
672
+ type: ClaudeAgent
673
+ connectionId: claude
674
+ properties:
675
+ model: claude-haiku-4-5
676
+ instructions: You research signup data and summarize findings.
677
+ maxSteps: 5
678
+ tools:
679
+ - lookup-signups
680
+
681
+ api:
682
+ - id: daily-research
683
+ type: Api
684
+ routine:
685
+ - id: research
686
+ type: CallAgent
687
+ properties:
688
+ agentId: research_agent
689
+ prompt: Summarize yesterday's signups and flag anomalies.
690
+
691
+ - id: send_report
692
+ type: SendGridMail
693
+ connectionId: email
694
+ properties:
695
+ to: team@example.com
696
+ subject: Daily signup report
697
+ text:
698
+ _step: research.text
699
+ ```
700
+
701
+ To let the agent see files, pass them with `files`. Here an endpoint reads a ticket, signs a link to its screenshot with an S3 request and hands it to the agent. The storage key comes from the ticket, not from the payload, so a caller names a ticket and cannot have any file in the bucket signed:
702
+
703
+ ```yaml
704
+ api:
705
+ - id: scope-ticket
706
+ type: Api
707
+ routine:
708
+ - id: get_ticket
709
+ type: MongoDBFindOne
710
+ connectionId: tickets
711
+ properties:
712
+ query:
713
+ _id:
714
+ _payload: ticket_id
715
+ - id: screenshot_link
716
+ type: AwsS3PresignedGetObject
717
+ connectionId: files
718
+ properties:
719
+ key:
720
+ _step: get_ticket.screenshot_key
721
+ expires: 600
722
+ - id: scope
723
+ type: CallAgent
724
+ properties:
725
+ agentId: scope_agent
726
+ prompt:
727
+ _string.concat:
728
+ - 'Scope this ticket: '
729
+ - _step: get_ticket.description
730
+ files:
731
+ - url:
732
+ _step: screenshot_link
733
+ mediaType: image/png
734
+ ```
735
+
736
+ Headless agent runs differ from interactive chat in a few ways:
737
+
738
+ - **Tool approval is not supported.** Tools configured with `confirm: true` auto-execute — there is no client to approve them. The build emits a warning when a `CallAgent` step references an agent with confirm tools.
739
+ - **No page context.** The `update-page-state` tool is not available, and no conversation title is generated.
740
+ - **Hooks still fire.** Agent [server hooks](/agent-server-hooks) (`onStart`, `onStepFinish`, `onFinish`, etc.) run as endpoint calls — useful for logging and persistence. `dataParts` returned by `onFinish` endpoints are ignored (there is no stream to write to), and the `messages` in the `onFinish` payload are model messages rather than UI messages.
741
+ - **Authorization is per tool endpoint.** Each tool call authorizes against that endpoint's `auth` config with the caller's identity. In a system context with no user, tools calling protected endpoints will fail.
742
+
743
+ Agent tool and hook endpoint calls share the same depth cap of 10 as `CallApi`, so mutually recursive agent and endpoint configurations terminate with an error instead of looping forever.
744
+
745
+ ## Validating Data As A Routine Step
746
+
747
+ API routines can validate any value against a JSON Schema using `ValidateSchema` steps. This is useful for guarding endpoint inputs that need stricter checks than the endpoint's request schema enforces, or for asserting the shape of data returned by a prior step before it flows downstream.
748
+
749
+ `ValidateSchema` is a built-in step. It requires no `connectionId` and no plugin install. It runs against the shared Ajv instance used by the rest of Lowdefy, so all standard JSON Schema features are available:
750
+
751
+ - All formats from [ajv-formats](https://ajv.js.org/packages/ajv-formats.html) (`email`, `uri`, `uuid`, `date`, `date-time`, `ipv4`, `ipv6`, …).
752
+ - The `instanceof`, `transform`, and `regexp` keywords from [ajv-keywords](https://ajv.js.org/packages/ajv-keywords.html).
753
+ - The `errorMessage` keyword from [ajv-errors](https://ajv.js.org/packages/ajv-errors.html) for custom error messages.
754
+
755
+ See [ajv.js.org](https://ajv.js.org/json-schema.html) for the full keyword reference.
756
+
757
+ A `ValidateSchema` step has:
758
+
759
+ - `id: string`: **Required** - A unique step id within the routine.
760
+ - `type: ValidateSchema`: **Required** - Identifies this as a validation step.
761
+ - `properties.schema: object`: **Required** - The JSON Schema to validate against. **Operators are evaluated**, so `_ref` and `_var` work for sourcing schemas from files or app state.
762
+ - `properties.data: any`: **Required** - The value to validate. **Operators are evaluated**.
763
+ - `properties.throwOnInvalid: boolean`: Optional, default `true`. When `true`, invalid data short-circuits the routine with an error response and the AJV errors attached as `error.cause`. When `false`, the routine continues and the validation result is exposed as the step result for downstream branching.
764
+
765
+ The step always records `{ valid, errors }` as its result, available downstream as `_step.<stepId>.valid` and `_step.<stepId>.errors`.
766
+
767
+ ###### Guard endpoint input (default throw)
768
+
769
+ ```yaml
770
+ api:
771
+ - id: create_user
772
+ type: Api
773
+ routine:
774
+ - id: validate_input
775
+ type: ValidateSchema
776
+ properties:
777
+ schema:
778
+ type: object
779
+ required: [email, name]
780
+ additionalProperties: false
781
+ properties:
782
+ email: { type: string, format: email }
783
+ name: { type: string, minLength: 1, maxLength: 80 }
784
+ age: { type: integer, minimum: 0 }
785
+ data:
786
+ _payload: true
787
+
788
+ - id: insert_user
789
+ type: MongoDBInsertOne
790
+ connectionId: app_db
791
+ properties:
792
+ collection: users
793
+ doc:
794
+ _payload: true
795
+
796
+ - :return:
797
+ userId:
798
+ _step: insert_user.insertedId
799
+ ```
800
+
801
+ If the request payload is missing `email`, the routine errors out with the AJV failure details and `insert_user` never runs.
802
+
803
+ ###### Inspect-and-branch (`throwOnInvalid: false`)
804
+
805
+ Set `throwOnInvalid: false` to keep going on failure — then use `:if` to react to `_step.<stepId>.valid`:
806
+
807
+ ```yaml
808
+ routine:
809
+ - id: check_input
810
+ type: ValidateSchema
811
+ properties:
812
+ schema:
813
+ type: object
814
+ required: [email]
815
+ properties:
816
+ email: { type: string, format: email }
817
+ data:
818
+ _payload: true
819
+ throwOnInvalid: false
820
+
821
+ - :if:
822
+ _eq:
823
+ - _step: check_input.valid
824
+ - false
825
+ :then:
826
+ - :reject:
827
+ message: 'Invalid input'
828
+ errors:
829
+ _step: check_input.errors
830
+
831
+ - id: send_welcome
832
+ type: SendgridMailSend
833
+ connectionId: mailer
834
+ properties:
835
+ to:
836
+ _payload: email
837
+ template: welcome
838
+ ```
839
+
840
+ ###### Validate a prior step's output
841
+
842
+ `schema` and `data` are both operator-evaluated, so any value reachable in the routine context can be checked — payload, prior step results, items in a loop, etc.
843
+
844
+ ```yaml
845
+ routine:
846
+ - id: load_profile
847
+ type: MongoDBFindOne
848
+ connectionId: app_db
849
+ properties:
850
+ collection: profiles
851
+ query:
852
+ _id:
853
+ _payload: userId
854
+
855
+ - id: assert_profile_shape
856
+ type: ValidateSchema
857
+ properties:
858
+ schema:
859
+ type: object
860
+ required: [_id, tier]
861
+ properties:
862
+ _id: { type: string }
863
+ tier: { type: string, enum: [free, pro, enterprise] }
864
+ data:
865
+ _step: load_profile
866
+ ```
867
+
868
+ ## Validating Dynamic Content As A Routine Step
869
+
870
+ `ValidateDynamic` checks block config against a [dynamic blocks policy](/dynamic-page-content#dynamic-blocks-policies) with the same function a Dynamic block runs at page get, so content that passes here renders there. `DescribeDynamicPolicy` returns what a policy allows. Both are built-in steps: no `connectionId`, no plugin install.
871
+
872
+ A `ValidateDynamic` step has:
873
+
874
+ - `id: string`: **Required** - A unique step id within the routine.
875
+ - `type: ValidateDynamic`: **Required**
876
+ - `properties.policy: string`: **Required** - The policy id, as a literal string.
877
+ - `properties.blocks: object[]`: **Required** - The content to check. **Operators are evaluated**, so read it with `_step` or `_payload`.
878
+ - `properties.throwOnInvalid: boolean`: Optional, default `true`. When `true`, invalid content ends the routine with an error. When `false`, the routine continues.
879
+
880
+ The step result is `{ valid, errors, blocks }`. Each error has `path` (a dot path into the content, such as `blocks.2.properties.title`), `rule` (such as `policy.blocks`, `policy.urls`, `limits.depth` or `schema`) and `message`. In the endpoint a Dynamic block calls, `_step: <stepId>.blocks` of a passing step with the block's policy is returned as config.
881
+
882
+ A `DescribeDynamicPolicy` step has `id`, `type: DescribeDynamicPolicy` and `properties.policy`. Its result lists the policy's `blocks` (each with its properties schema), `actions` and `operators` (each with its params schema), `endpoints`, `requests`, `links`, `state`, `html` and `limits`.
883
+
884
+ ###### Generate, check and store a form
885
+
886
+ ```yaml
887
+ api:
888
+ - id: generate_form
889
+ type: Api
890
+ routine:
891
+ - id: vocabulary
892
+ type: DescribeDynamicPolicy
893
+ properties:
894
+ policy: generated_form
895
+ - id: attempt
896
+ type: GenerateObject
897
+ connectionId: model
898
+ properties:
899
+ # prompt built from _payload.description and _step.vocabulary
900
+ - id: check
901
+ type: ValidateDynamic
902
+ properties:
903
+ policy: generated_form
904
+ blocks:
905
+ _step: attempt.blocks
906
+ throwOnInvalid: false
907
+ - :if:
908
+ _step: check.valid
909
+ :then:
910
+ - id: store
911
+ type: MongoDBInsertOne
912
+ connectionId: forms
913
+ properties:
914
+ doc:
915
+ blocks:
916
+ _step: check.blocks
917
+ - :return:
918
+ valid: true
919
+ :else:
920
+ - :return:
921
+ valid: false
922
+ errors:
923
+ _step: check.errors
924
+ ```
925
+
926
+ ## Rendering Notifications As A Routine Step
927
+
928
+ API routines render a [notification](/notifications) to an email with `RenderNotification` steps. The step renders one notification item against a template defined in the app's `notifications:` section and returns the rendered content — it does **not** store or send anything. Storing a record, sending the email, and tracking delivery are ordinary routine steps you compose around it (or that the [`modules-mongodb` notifications module](https://github.com/lowdefy/modules-mongodb) composes for you).
929
+
930
+ `RenderNotification` is a built-in step. It requires no `connectionId` and no plugin install.
931
+
932
+ A `RenderNotification` step has:
933
+
934
+ - `id: string`: **Required** - A unique step id within the routine.
935
+ - `type: RenderNotification`: **Required** - Identifies this as a render step.
936
+ - `properties.notificationId: string`: **Required** - The id of the notification in the `notifications:` section to render. **Operators are evaluated**.
937
+ - `properties.data: object`: **Required** - The data for **one** notification (the recipient and template data). Must be a single object — to render a batch, iterate with a [`:for`](/for) control and render one item per step. **Operators are evaluated**.
938
+ - `properties.serverUrl: string`: The absolute origin used to build link URLs (for example `https://myapp.com`). Defaults to the `url` of the current environment in [`config.environments`](/lowdefy-schema), and on the dev server (`lowdefy dev`) to the request origin. Required when the item carries page links and neither is available.
939
+ - `properties.landingPage: string | object`: The page to route email links through, by page id (for example `notifications-link`) or `{ pageId, pathParams }` when its path has parameters. Its URL path is built from the page's path like any other link, so a landing page with a `path` works. It lets a landing page mark the notification read before redirecting. A value that names no page, such as a URL path (`/notifications/link`), fails the step: v7 changed this property from a path to a page id (see [Version 6 to Version 7](/v6-to-v7)). When unset, links go directly to their target pages.
940
+ - `properties.recordId: string`: The record id embedded in landing-page link URLs. Required when `landingPage` is set and the item has links — usually a `_uuid` minted earlier in the routine.
941
+
942
+ The step result contains:
943
+
944
+ - `subject: string`: The interpolated subject line.
945
+ - `title: string`: The interpolated title (falls back to `subject`).
946
+ - `preview: string`: A short preview string for inbox listings (the template's `preview`, else a markdown-stripped excerpt of the message).
947
+ - `html: string`: The rendered email as HTML.
948
+ - `text: string`: The rendered email as plain text.
949
+ - `data: object`: The item with its links resolved to URLs.
950
+
951
+ ```yaml
952
+ api:
953
+ - id: notify-task-assigned
954
+ type: Api
955
+ routine:
956
+ - id: render
957
+ type: RenderNotification
958
+ # Render one item; see /notifications for the notifications: section.
959
+ properties:
960
+ notificationId: task-assigned
961
+ data:
962
+ _payload: item
963
+ serverUrl: https://myapp.com
964
+
965
+ - id: send
966
+ type: SMTPMailSend
967
+ connectionId: smtp
968
+ properties:
969
+ to:
970
+ _payload: item.contact.email
971
+ subject:
972
+ _step: render.subject
973
+ html:
974
+ _step: render.html
975
+ text:
976
+ _step: render.text
977
+ ```
978
+
979
+ See [Notifications](/notifications) for the `notifications:` section, the built-in templates, and how link URLs are composed.
980
+
981
+ ## Internal API Endpoints
982
+
983
+ Endpoints with `type: InternalApi` are only callable from other endpoints via `CallApi` steps. They cannot be called from client pages using the `CallAPI` action, and HTTP requests to them return a "does not exist" error.
984
+
985
+ Use `InternalApi` for endpoints that contain sensitive server-side logic that should never be triggered directly from the client — for example, sending emails, processing payments, or auditing events.
986
+
987
+ ```yaml
988
+ api:
989
+ - id: charge_payment
990
+ type: InternalApi
991
+ routine:
992
+ - id: charge
993
+ type: AxiosHttp
994
+ connectionId: payment-gateway
995
+ properties:
996
+ data:
997
+ amount:
998
+ _payload: amount
999
+ token:
1000
+ _payload: payment_token
1001
+ - :return:
1002
+ _step: charge
1003
+
1004
+ - id: checkout
1005
+ type: Api # Callable from the client
1006
+ routine:
1007
+ - id: process_payment
1008
+ type: CallApi
1009
+ properties:
1010
+ endpointId: charge_payment # Can call InternalApi endpoints
1011
+ payload:
1012
+ amount:
1013
+ _payload: total
1014
+ payment_token:
1015
+ _payload: token
1016
+ - :return:
1017
+ payment:
1018
+ _step: process_payment
1019
+ ```
1020
+
1021
+ If a client-side `CallAPI` action targets an `InternalApi` endpoint, the build produces a warning in dev mode and an error in production builds.
1022
+
1023
+ ## Operators
1024
+
1025
+ The following operators are specific to API endpoints:
1026
+
1027
+ - [`_item`](/_item) - Access current item in :for and :parallel_for loops.
1028
+ - [`_state`](/_state) - Access server-side state set with :set_state.
1029
+ - [`_step`](/_step) - Access results from requests in previous steps.
1030
+
1031
+ API endpoints also have access to all operators available on the server, including:
1032
+
1033
+ - [`_payload`](/_payload) - Access the payload sent from the client.
1034
+ - [`_secret`](/_secret) - Access secrets from environment variables or secrets configuration.
1035
+ - [`_user`](/_user) - Access authenticated user information.
1036
+
1037
+ ### Accessing Step Results
1038
+
1039
+ Use the [`_step`](/_step) operator to access results from previously executed steps:
1040
+
1041
+ ```yaml
1042
+ - id: get_user
1043
+ type: MongoDBFindOne
1044
+ connectionId: users
1045
+ properties:
1046
+ query:
1047
+ email:
1048
+ _payload: email
1049
+
1050
+ - id: get_orders
1051
+ type: MongoDBAggregation
1052
+ connectionId: orders
1053
+ properties:
1054
+ pipeline:
1055
+ - $match:
1056
+ user_id:
1057
+ _step: get_user._id # Access the _id from the get_user request
1058
+ ```
1059
+
1060
+ ## CallAPI Action
1061
+
1062
+ Use the `CallAPI` action to call your API endpoints from pages. Read more about the `CallAPI` action [here](/CallAPI).
1063
+
1064
+ ###### Basic example:
1065
+
1066
+ ```yaml
1067
+ blocks:
1068
+ - id: user_id_input
1069
+ type: TextInput
1070
+ properties:
1071
+ title: User ID
1072
+
1073
+ - id: fetch_user_btn
1074
+ type: Button
1075
+ properties:
1076
+ title: Fetch User Data
1077
+ events:
1078
+ onClick:
1079
+ - id: call_user_api
1080
+ type: CallAPI
1081
+ params:
1082
+ endpoint_id: get_user_data
1083
+ payload:
1084
+ user_id:
1085
+ _state: user_id_input
1086
+
1087
+ - id: set_user_data
1088
+ type: SetState
1089
+ params:
1090
+ user_data:
1091
+ _actions: call_user_api.response.user
1092
+
1093
+ - id: user_display
1094
+ type: Descriptions
1095
+ properties:
1096
+ items:
1097
+ _state: user_data
1098
+ ```
1099
+
1100
+ ###### Error handling example:
1101
+
1102
+ ```yaml
1103
+ events:
1104
+ onClick:
1105
+ try:
1106
+ - id: call_process_data_api
1107
+ type: CallAPI
1108
+ params:
1109
+ endpoint_id: process_data
1110
+ payload:
1111
+ data:
1112
+ _state: form_data
1113
+
1114
+ - id: show_success
1115
+ type: DisplayMessage
1116
+ params:
1117
+ content: 'Data processed successfully!'
1118
+ status: success
1119
+
1120
+ - id: update_state
1121
+ type: SetState
1122
+ params:
1123
+ result:
1124
+ _actions: call_process_data_api.response
1125
+
1126
+ catch:
1127
+ - id: update_state
1128
+ type: SetState
1129
+ params:
1130
+ error_message:
1131
+ _actions: call_process_data_api.error.message
1132
+ ```
1133
+
1134
+ ### \_api Operator
1135
+
1136
+ The [`_api`](/_api) operator returns the response value of an API call. If the API has not yet been called, or is still executing, the returned value is `null`.
1137
+
1138
+ ###### Using an API response:
1139
+
1140
+ ```yaml
1141
+ blocks:
1142
+ - id: loading_text
1143
+ type: Html
1144
+ visible:
1145
+ _api: fetch_data.loading
1146
+ properties:
1147
+ html: '<div class="secondary">Loading...</div>'
1148
+
1149
+ - id: error_alert
1150
+ type: Alert
1151
+ visible:
1152
+ _not:
1153
+ _api: fetch_data.success
1154
+ properties:
1155
+ type: error
1156
+ message:
1157
+ _api: fetch_data.error.message
1158
+
1159
+ - id: data_display
1160
+ type: Descriptions
1161
+ properties:
1162
+ items:
1163
+ _api: fetch_data.response
1164
+ ```
1165
+
1166
+ ## Complex Example: Order Processing API
1167
+
1168
+ Here's a comprehensive example showing various features:
1169
+
1170
+ ```yaml
1171
+ lowdefy: '6.1.0'
1172
+ auth:
1173
+ api:
1174
+ protected: true
1175
+ roles:
1176
+ user:
1177
+ - process_order
1178
+
1179
+ api:
1180
+ - id: process_order
1181
+ type: Api
1182
+ routine:
1183
+ # Validate order
1184
+ - id: validate_order
1185
+ type: MongoDBFindOne
1186
+ connectionId: orders
1187
+ properties:
1188
+ query:
1189
+ _id:
1190
+ _payload: order_id
1191
+ status: 'pending'
1192
+ user_id:
1193
+ _user: id # Ensure user owns this order
1194
+
1195
+ - :if:
1196
+ _not:
1197
+ _step: validate_order
1198
+ :then:
1199
+ :reject: 'Order not found or already processed'
1200
+
1201
+ # Process items in parallel
1202
+ - :parallel_for: item
1203
+ :in:
1204
+ _step: validate_order.items
1205
+ :do:
1206
+ - id: check_inventory
1207
+ type: MongoDBFindOne
1208
+ connectionId: products
1209
+ properties:
1210
+ query:
1211
+ _id:
1212
+ _item: item.product_id
1213
+ inventory:
1214
+ $gte:
1215
+ _item: item.quantity
1216
+
1217
+ - :if:
1218
+ _not:
1219
+ _step: check_inventory
1220
+ :then:
1221
+ :throw: 'Insufficient inventory'
1222
+
1223
+ # Try payment processing
1224
+ - :try:
1225
+ - id: process_payment
1226
+ type: AxiosHttp
1227
+ connectionId: payment-gateway
1228
+ properties:
1229
+ data:
1230
+ amount:
1231
+ _step: validate_order.total
1232
+ currency: 'USD'
1233
+ source:
1234
+ _payload: payment_token
1235
+
1236
+ :catch:
1237
+ - id: mark_payment_failed
1238
+ type: MongoDBUpdateOne
1239
+ connectionId: orders
1240
+ properties:
1241
+ filter:
1242
+ _id:
1243
+ _payload: order_id
1244
+ update:
1245
+ $set:
1246
+ status: 'payment_failed'
1247
+ failed_at:
1248
+ _date: now
1249
+
1250
+ - :reject: 'Payment processing failed'
1251
+
1252
+ # Update order status
1253
+ - id: complete_order
1254
+ type: MongoDBUpdateOne
1255
+ connectionId: orders
1256
+ properties:
1257
+ filter:
1258
+ _id:
1259
+ _payload: order_id
1260
+ update:
1261
+ $set:
1262
+ status: 'completed'
1263
+ payment_id:
1264
+ _step: process_payment.data.id
1265
+ completed_at:
1266
+ _date: now
1267
+
1268
+ # Update inventory
1269
+ - :for: item
1270
+ :in:
1271
+ _step: validate_order.items
1272
+ :do:
1273
+ - id: reduce_inventory
1274
+ type: MongoDBUpdateOne
1275
+ connectionId: products
1276
+ properties:
1277
+ filter:
1278
+ _id:
1279
+ _item: item.product_id
1280
+ update:
1281
+ $inc:
1282
+ inventory: -1
1283
+
1284
+ # Send confirmation email
1285
+ - id: send_confirmation
1286
+ type: SendGridMail
1287
+ connectionId: email-service
1288
+ properties:
1289
+ to:
1290
+ _step: validate_order.customer_email
1291
+ template_id: 'order_confirmation'
1292
+ dynamic_template_data:
1293
+ order_id:
1294
+ _payload: order_id
1295
+ total:
1296
+ _step: validate_order.total
1297
+
1298
+ # Return success
1299
+ - :return:
1300
+ success: true
1301
+ order_id:
1302
+ _payload: order_id
1303
+ payment_id:
1304
+ _step: process_payment.data.id
1305
+ message: 'Order processed successfully'
1306
+ ```
1307
+
1308
+ ### TLDR
1309
+
1310
+ - Lowdefy APIs create custom server-side endpoints that execute complex logic.
1311
+ - Routines define the execution flow using arrays, requests and control structures.
1312
+ - Control structures like [`:if`](/:if), [`:for`](/:for), [`:parallel`](/:parallel), and [`:try`](/:try) enable sophisticated flows.
1313
+ - Requests make requests to connections and can access results using [`_step`](/_step).
1314
+ - `CallApi` steps call other endpoints server-side with isolated `_step` and `_payload` namespaces.
1315
+ - `InternalApi` endpoints are server-only — callable from other endpoints but not from client pages.
1316
+ - The [`CallAPI`](/CallAPI) action is used to invoke APIs from the client with payloads.
1317
+ - Server-side execution provides access to secrets, connections, and server operators.
1318
+ - Responses are controlled with [`:return`](/:return) (success) and [`:reject`](/:reject) (user errors).
1319
+ - A [`:reject`](/:reject) is a reply, not an exception, and is never caught by [`:try`](/:try)/`:catch`; [`:throw`](/:throw) is.