# Calling another service from an app

An app can use a person's own account at another service: list their GitHub repositories, read their calendar, create an issue. The app's frame has no network and never holds a key. You declare what the app may call in the manifest; each person connects their own credential on a Nerd Out page; the app calls `nerd.integrations.call(...)` and Nerd Out's server sends the request.

Use an integration when the data is **a person's own** or the app **changes something** elsewhere. For public data everyone sees the same (weather, rates), use `sources`: it is simpler and needs nobody to connect anything.

**You never see or handle a key.** Never ask the owner for one, never put one in a manifest, a URL, sample data or your chat, and never build a field in the app that asks for one (an app that does is held for review). Tell the owner: "Open the app and tap Connect GitHub."

Start from the `connected` template (https://nerdout.com/workshop/sdk/templates/connected.json): a list from GitHub with every state built, what was fetched kept in records, and a confirmed write.

## 1. Declare it

```json
"integrations": {
  "github": {
    "label": "GitHub",
    "origin": "https://api.github.com",
    "auth": { "kind": "bearer" },
    "headers": { "Accept": "application/vnd.github+json" },
    "operations": {
      "listRepos": {
        "summary": "Read your repositories",
        "method": "GET",
        "path": "/user/repos",
        "query": { "page": { "type": "integer", "min": 1, "max": 20 }, "per_page": { "const": 30 }, "sort": { "enum": ["updated", "pushed"], "optional": true } },
        "effect": "read",
        "result": { "fields": ["id", "full_name", "updated_at"], "maxItems": 100 }
      },
      "createIssue": {
        "summary": "Create an issue in a repository",
        "method": "POST",
        "path": "/repos/{owner}/{repo}/issues",
        "params": { "owner": { "type": "string", "format": "segment" }, "repo": { "type": "string", "format": "segment" } },
        "body": { "title": { "type": "string", "maxLength": 200 }, "body": { "type": "string", "maxLength": 4000, "optional": true } },
        "effect": "write",
        "confirm": true,
        "result": { "fields": ["number", "html_url"] }
      }
    },
    "setupUrl": "https://github.com/settings/tokens",
    "setupHint": "A fine-grained token with read access to repositories, and issues write to create them."
  }
}
```

Not for `device` scope (nobody is signed in). Up to 8 integrations, 32 operations each.

| Key | Rule |
| --- | --- |
| name (`github`) | Lower-case letters, digits and dashes. |
| `label` | The service's name as people know it. |
| `origin` | One exact `https://` origin, no path. Every operation goes there and nowhere else. |
| `auth` | How the credential is sent. Sign-in: an `oauth2` block (below). A pasted key: `{ "kind": "bearer" }`, `{ "kind": "header", "header": "X-Api-Key", "prefix"?: "Token " }`, `{ "kind": "basic" }` (a user name and password), `{ "kind": "query", "param": "apikey" }` (avoid when the provider offers a header). |
| `headers` | Up to 8 fixed headers (`Accept`, an API version). Never the credential; no header is set at run time. |
| `setupUrl`, `setupHint` | Where a person creates their key, and one or two sentences on which permissions it needs for these operations. Ask for the least. |

### Operations

An app calls **declared operations with typed inputs, never free paths**. If the app needs another endpoint, declare another operation.

| Key | Rule |
| --- | --- |
| name (`listRepos`) | camelCase. |
| `summary` | What it does in the words a person reads before connecting, up to 80 characters: "Read your repositories", "Create an issue in a repository". |
| `method`, `effect` | `GET` and `HEAD` are `"read"`; `POST`, `PUT`, `PATCH`, `DELETE` are `"write"`. |
| `path` | Starts with `/`. Fixed segments and whole-segment `{placeholders}`, each declared in `params`. No query, no `..`. |
| `params` | Path values: an `integer`, an `enum`, a `const`, or a string with `"format": "segment"`, `"slug"` or `"uuid"`. |
| `query`, `body` | Up to 16 declared values each. A body is JSON, or a form with `"bodyEncoding": "form"`. |
| `confirm` | On a write a person should see first: Nerd Out shows the service, the summary and every input, and sends only on their yes. Use it for anything they would not expect to happen by itself. |
| `result` | What of the answer reaches the app: `arrayAt` (a dotted path to the list), `fields` (dotted paths to keep in each item), `maxItems`. Name only what the app shows. Required with `query` auth. |

**Input types:** `integer`, `number` (`min`, `max`); `boolean`; `string` (`maxLength` up to 1024, and a `format` from `segment`, `slug`, `email`, `uuid`, `date`); `datetime`; `{ "enum": [...] }`; `{ "const": value }` (always sent, never supplied by the app). In a body also `{ "type": "array", "items": <one of those>, "maxItems" }` and `{ "type": "object", "fields": { ... } }`, one level deep. Add `"optional": true` to let the app leave one out. There are no patterns, and a provider's own "next page" address is never an input: page with a number.

One input name belongs to one group. The app passes them all in one object.

### Signing in instead of a key (OAuth 2.0)

When the provider offers sign-in (GitHub, Google, most large services), prefer it: people tap "Sign in with GitHub" instead of making a token.

```json
"auth": {
  "kind": "oauth2",
  "authorizeUrl": "https://github.com/login/oauth/authorize",
  "tokenUrl": "https://github.com/login/oauth/access_token",
  "scopes": ["read:user", "public_repo"],
  "identity": { "path": "/user", "field": "login" }
}
```

- `authorizeUrl`, `tokenUrl`, optional `revokeUrl`: copied from the provider's OAuth documentation.
- `scopes`: the least the operations need. The operations still bound what the app can do: a broad scope behind read-only operations cannot write.
- `pkce` (default true); `tokenAuth`: `"body"` (the default; GitHub, Google) or `"basic"`.
- `authorizeParams`: extra sign-in parameters a provider needs. For Google, `{ "access_type": "offline", "prompt": "consent" }`, or tokens stop working after an hour.
- `identity`: an optional path under `origin` and the field that names the account, shown as "as brian".

**The owner sets it up once.** Nerd Out registers nothing with providers. The owner creates an OAuth app in the provider's developer settings with the callback address shown on their app page (https://nerdout.com/playground/integrations/callback), then pastes its client ID and secret there, in "Sign-in setup" (under More, in the Agent row). Until they do, the status is `not_configured`. Write `setupUrl` and `setupHint` for that: where to create the OAuth app and which scopes to allow. Tell the owner this step exists, in one sentence, when you propose the integration; if it is more than they want, offer a pasted key instead where the provider has one.

Tokens are refreshed for you. A token the provider no longer accepts turns the status to `needs_reconnect`.

## 2. Call it

```js
nerd.ui.connect(el, "github", { text: "Connect GitHub to see your repositories.", onChange: (state) => { if (state === "connected") load(); } });

async function load() {
  const r = await nerd.integrations.call("github", "listRepos", { page: 1 });
  if (r.status !== 200) return showTrouble(r.status);   // the provider's own error is an answer, not a rejection
  render(r.data);                                        // only the fields the operation's result names
}
```

- `nerd.integrations.call(name, operation, inputs)` resolves `{ status, data, message? }`. `data` is the 2xx JSON answer cut to `result`; for any other status it is `null` and `message` holds a little of what the provider said. **Always look at `status`.**
- It rejects with our codes: `not_connected`, `needs_reconnect`, `not_configured`, `signed_out`, `shared_read_only` (a change through the owner's shared connection that the owner has not allowed), `confirm_declined`, `invalid_input`, `rate_limited`, `timeout`, `offline`, `upstream_unreachable`, `app_updated`, `unavailable`. `nerd.ui.explain(error)` has words for each.
- `nerd.integrations.status()` and `.observe(fn)` give `{ github: "connected" | "not_connected" | "needs_reconnect" | "not_configured" | "signed_out" | "unavailable" }`.
- `nerd.ui.connect(el, name, { text, onChange })` draws the not-connected state with a Connect button that opens Nerd Out's own sheet, and nothing once connected. Use it on every screen that needs the integration, and load only after `onChange` says `"connected"`.
- A call that times out may still have happened. After a write that ends in `timeout`, read back before trying again, and design writes to be safe to repeat.
- Nothing is cached for you. Keep what the app needs between visits in `nerd.data`, and say when it was fetched.
- Limits: 8 KiB of inputs per call, 1 MiB of result, 25 seconds, 60 calls a minute from one open app. Do not call in a loop or on a timer; call when a screen opens and when the person asks.

## 3. Who can use it

- **Each signed-in person the owner invited** connects their own account, once, in the sheet. Other people's connections are never shared with them.
- **The owner may share theirs** with the people they invite, for reading, and separately for changes. The app cannot tell whose connection answered, and should not care.
- **A visitor to an open app** who was not invited sees `unavailable`. Design the screen to still make sense: say what the app does and that the owner has to invite them.

## 4. Sample data

Previews and the hosted check never reach a provider. Give every operation its answers in `sampleData.$integrations`, written from the provider's documentation:

```json
"$integrations": {
  "github": {
    "listRepos": {
      "ok": { "status": 200, "json": [{ "id": 1, "full_name": "nerd-out/site", "updated_at": "2026-11-07T14:30:00Z" }] },
      "empty": { "status": 200, "json": [] },
      "failure": { "status": 503, "json": { "message": "Service unavailable" } }
    },
    "createIssue": { "ok": { "status": 201, "json": { "number": 42, "html_url": "https://github.com/nerd-out/site/issues/42" } } }
  }
}
```

`ok` is required; `empty` and `failure` are how the other two screens get built. Write the answer the provider really sends (the whole item, not only your fields): the preview cuts it to `result` the way the server will. An integration with sample answers counts as connected in a preview. `validate` warns about an operation with none.

In the check (https://nerdout.com/workshop/sdk/check.md), three steps show the screens a person will meet:

```json
{ "integration": ["github", "listRepos", "empty"] }
{ "integration": ["github", "listRepos", "failure"] }
{ "integration": ["github", "disconnect"] }
```

A step changes what the next call answers; it does not make the app call again, so follow it with whatever makes the app load (reopen the tab, tap Refresh). Photograph all four states: full, empty, failing, not connected.

## 5. What to tell the owner

- Which service the app uses, what it can do there in plain words, and that a change asks first.
- That each person connects their own account by opening the app and tapping Connect, and that they can share theirs with the people they invite from the same sheet.
- Where to create the key (`setupUrl`) and which permissions to give it. Nothing more.

The context's `integrations` says, per integration, how many people have connected and whether the owner has. It never holds a key.
