UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

240 lines (193 loc) • 12.6 kB
--- name: integrations description: >- Call a third-party service connected as an integration: defineIntegration from @softr/sdk declares the one method and endpoint it allows, and integration.createFetcher from @softr/sdk/server calls it. metadata: type: sub-skill library: softr-sdk library_version: 1.19.0 --- **Boundary.** `integration` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineIntegration` and every type come from `@softr/sdk` and can be imported anywhere. # Integrations `integration.createFetcher` calls a third-party API through Softr's authenticated proxy. It adds the connected account's credentials automatically — you never set API keys or auth headers yourself. **Every call acts as that one account, whoever the visitor is**, so take what a call reaches, such as a customer or a channel, from the session or a record the server read, never from the arguments the browser sends. ## Setup ```ts import { createServerFn } from '@tanstack/react-start' import { defineIntegration } from '@softr/sdk' import { auth, integration } from '@softr/sdk/server' ``` ## Reading connected integrations from the prompt When the user attaches integrations to the chat, they appear in the `## Attached integrations` section of the prompt in this form: ``` - integration `<integrationId>`, type `GMAIL`, database `<databaseId>` "Gmail" - integration `<integrationId>`, type `GMAIL` ``` Pass the `integration` value as `integrationId` in `defineIntegration`. The `database` value is the table coordinate; integrations do not use it, so do not pass it anywhere. Use `integrationType` (e.g. `GMAIL`) to look up the base URL from the reference table below — then construct the full URL path in the `url` field. Pass query parameters via `query` on the fetcher call, not in the declared `url`. Either shape configures `defineIntegration`. An entry with no `database` coordinate carries the `integrationId`, which is all the call needs. ## Declare the integration action ```ts const listCalendarEvents = defineIntegration({ id: 'listCalendarEvents', integrationId: '25d60213-ef4f-4fa0-b094-a46931b2d120', method: 'GET', url: 'https://www.googleapis.com/calendar/v3/calendars/primary/events', permissions: { userGroupTypes: ['LOGGED_IN_USERS'] }, }) ``` Write the object inline in `defineIntegration`. Passing it through a variable widens the types. The action allows exactly one HTTP `method` and one endpoint `url`. The proxy denies a call whose method does not match. So **declare one action per operation** — reading a record and deleting it are two actions, each with its own `id` and its own audience. Declare the **full endpoint path**, not just the host — one action names one endpoint. For a dynamic path segment, write a `{placeholder}` token with any name — for example `url: 'https://api.stripe.com/v1/customers/{id}'` or `url: 'https://api.stripe.com/v1/invoices/{invoiceId}/void'`. Keep query parameters out of the declared `url`; add them to the call. ## Core pattern `integration.createFetcher(action)` binds the action and returns a fetcher function. The `method` and `url` come from the action — you do not repeat them on the call. Pass an optional init object with: - `params` — fills `{placeholder}` tokens in the declared url, one key per token. Pass each value raw: the SDK encodes it. - `query` — appended as a query string (`?key=value`). - `headers` — extra request headers. - `body` — request body string. - `signal` — abort signal. ```ts const getCalendarEvents = createServerFn().handler(async () => { const calendar = integration.createFetcher(listCalendarEvents) const now = new Date().toISOString() const res = await calendar({ query: { timeMin: now, singleEvents: 'true', orderBy: 'startTime', maxResults: '10' }, }) if (!res.ok) throw new Error(`Integration request failed: ${res.status} ${await res.text()}`) return res.json() }) ``` For a dynamic path segment, pass `params` matching each `{placeholder}` token. Here the customer comes from the visitor's own Users row, which `auth.currentUserRow` finds through `usersQuery`, the app's `defineQuery` on the Users table: ```ts const getStripeCustomer = defineIntegration({ id: 'getStripeCustomer', integrationId: 'wsint-stripe', method: 'GET', url: 'https://api.stripe.com/v1/customers/{id}', permissions: { userGroupTypes: ['LOGGED_IN_USERS'] }, }) const fetchCustomer = createServerFn({ method: 'GET' }) .handler(async ({ context }) => { const me = await auth.currentUserRow(context.user, usersQuery, 'email') const customerId = me?.fields.stripeCustomerId if (!customerId) throw new Error('No Stripe customer for this visitor') const stripe = integration.createFetcher(getStripeCustomer) const res = await stripe({ params: { id: customerId } }) if (!res.ok) throw new Error(`Stripe error: ${res.status} ${await res.text()}`) return res.json() }) ``` ## POST request ```ts const postSlackMessage = defineIntegration({ id: 'postSlackMessage', integrationId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', method: 'POST', url: 'https://slack.com/api/chat.postMessage', permissions: { userGroupTypes: ['LOGGED_IN_USERS'] }, }) const sendSlackMessage = createServerFn({ method: 'POST' }) .validator((data: { text: string }) => data) .handler(async ({ data }) => { const slack = integration.createFetcher(postSlackMessage) const res = await slack({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ channel: '#sales', text: data.text }), }) if (!res.ok) throw new Error(`Slack error: ${res.status} ${await res.text()}`) return res.json() }) ``` Do not add an `Authorization` key to `headers` — Softr injects the integration's credentials automatically. ## Calling an AI model **This is the path for the user's own provider account only.** An AI feature of the app's own — a summary, an extraction, a chat — runs on Softr's keys through an AI action, with nothing to connect and no key to ask for: load the `ai` sub-skill for it. Call a model through an integration only when the user chose their own OpenAI, Anthropic or Gemini account for the feature, in the prompt or when asked, and had it connected. **The model id comes from `ai_list_models`, never from memory.** Each entry of that list carries `providerModelId`, the id the provider's own API accepts, and `provider`: `anthropic` for an `ANTHROPIC_AI` integration, `openai` for `OPEN_AI`, `google_ai` for `GEMINI_AI`. Pick an entry of the integration's provider as the `ai` sub-skill's "Choose the model" says, and send its `providerModelId`. An id spelled from memory (`claude-3-5-…`, `gpt-4o`) names a model that no longer answers, and the error only shows up when the button is pressed. An AI integration is called like any other. For `ANTHROPIC_AI`, the action is `POST` on `https://api.anthropic.com/v1/messages`, the request carries the `anthropic-version` header and a body of `model`, `max_tokens`, `system` and `messages`, and the answer's text is in `content[].text`: ```ts const askClaude = defineIntegration({ id: 'askClaude', integrationId: '<the ANTHROPIC_AI integration id from the attached integrations>', method: 'POST', url: 'https://api.anthropic.com/v1/messages', permissions: { userGroupTypes: ['LOGGED_IN_USERS'] }, }) const claude = integration.createFetcher(askClaude) const res = await claude({ headers: { 'Content-Type': 'application/json', 'anthropic-version': '2023-06-01' }, body: JSON.stringify({ model: '<providerModelId of an anthropic entry of ai_list_models>', max_tokens: 1024, system: 'You write a short briefing for a sales team. Use only the facts given.', messages: [{ role: 'user', content: facts }], }), }) if (!res.ok) throw new Error(`AI error: ${res.status} ${await res.text()}`) const body = (await res.json()) as { content: Array<{ type: string; text?: string }> } const text = body.content.flatMap((block) => (block.type === 'text' && block.text ? [block.text] : [])).join('') ``` For `OPEN_AI`, the action is `POST` on `https://api.openai.com/v1/chat/completions` with a body of `model` and `messages` (the system text as the first message, role `system`); the answer's text is in `choices[0].message.content`. For `GEMINI_AI`, the action is `POST` on `https://generativelanguage.googleapis.com/v1beta/models/<providerModelId>:generateContent` with a body of `contents` (`[{ role: 'user', parts: [{ text }] }]`) and an optional `systemInstruction`; the answer's text is in `candidates[0].content.parts[].text`. Read the answer defensively: a refusal or an empty answer leaves the text out. ## Base URLs by integration type Match the `integrationType` from the attached integrations section to find the base URL: | integrationType | Base URL | | --- | --- | | ANTHROPIC_AI | `https://api.anthropic.com` | | APOLLO | `https://api.apollo.io` | | APIFY | `https://api.apify.com` | | ASANA | `https://app.asana.com` | | ATTIO | `https://api.attio.com` | | BASEROW | `https://api.baserow.io` | | BITLY | `https://api-ssl.bitly.com` | | BREVO | `https://api.brevo.com` | | CALCOM | `https://api.cal.com` | | CALENDLY | `https://api.calendly.com` | | COHERE | `https://api.cohere.com` | | DEEPL | `https://api.deepl.com` | | DEEP_SEEK_AI | `https://api.deepseek.com` | | DOCS_AUTOMATOR | `https://api.docsautomator.co` | | DOCUMINT | `https://api.documint.me` | | ELASTIC_EMAIL | `https://api.elasticemail.com` | | ELEVEN_LABS | `https://api.elevenlabs.io` | | FATHOM | `https://api.fathom.ai` | | FIRECRAWL | `https://api.firecrawl.dev` | | GEMINI_AI | `https://generativelanguage.googleapis.com` | | GMAIL | `https://gmail.googleapis.com` | | GOOGLE_CALENDAR | `https://www.googleapis.com` | | GRANOLA | `https://public-api.granola.ai` | | HUNTER | `https://api.hunter.io` | | INSTANTLY | `https://api.instantly.ai` | | LEMLIST | `https://api.lemlist.com` | | LINEAR | `https://api.linear.app` | | LINKUP | `https://api.linkup.so` | | LOOPS | `https://app.loops.so` | | MESSAGE_BIRD | `https://rest.messagebird.com` | | MICROSOFT_PLANNER | `https://graph.microsoft.com` | | MISTRAL_AI | `https://api.mistral.ai` | | OPEN_AI | `https://api.openai.com` | | OUTLOOK | `https://graph.microsoft.com` | | PADDLE | `https://api.paddle.com` | | PINECONE | `https://api.pinecone.io` | | PIPELINE_CRM | `https://api.pipelinecrm.com` | | POSTMARK | `https://api.postmarkapp.com` | | REPLICATE | `https://api.replicate.com` | | RESEND | `https://api.resend.com` | | SLACK | `https://slack.com/api` | | SMARTLEAD | `https://server.smartlead.ai` | | STRIPE | `https://api.stripe.com` | | TALLY | `https://api.tally.so` | | TELEGRAM | `https://api.telegram.org` | | TINYURL | `https://api.tinyurl.com` | | TRELLO | `https://api.trello.com` | | TWILIO | `https://api.twilio.com` | | TYPEFORM | `https://api.typeform.com` | | XERO | `https://api.xero.com` | | ZOOM | `https://api.zoom.us` | `REST_API` is a custom API, so it has no row here. Each connection has its own base URL, and `connect-a-service` says where to read it. ## When the type is in the table but nothing is attached The service is not out of reach, it is not connected yet. Load `connect-a-service` and ask the user for it: the answer carries the `integrationId` this skill needs. ## When the service is not a Softr integration If the API the user needs is not in the table above and needs no key, call it directly from a server function using the native `fetch`. If it needs a key or OAuth, load `connect-a-service` to connect it, then call it like any integration above. A key written into the code is in every code version and in the chat. ## Failure modes **Calling from client code.** `integration` is server-only. Importing it into a component or calling it outside a `createServerFn` handler fails the build or has no request context to act on. **Setting Authorization headers.** Softr injects credentials automatically. A manually set `Authorization` header overrides the injected one and the request is rejected by the third-party API. **Not checking `res.ok`.** The fetcher returns the proxied response as-is. A 4xx or 5xx from the third-party API is not thrown — call `res.ok` or `res.status` before calling `res.json()`. **Reusing one action for a different endpoint.** An action authorizes one `method` and one endpoint `url`. A different endpoint belongs to a different action — declare one for it, with its own audience.