# Convert an existing API

For a team that has an API today and wants AI agents to use it with a person's approval. This page is the method: go
through your endpoints one by one and decide, for each, what agents may do and what the person approves. The code
for each step is in [Accept AI agents in your app](https://docs.allowedby.com/guides/accept-agents) and in your [language guide](https://docs.allowedby.com/).

## 1. Sort every endpoint into one of three groups

List your endpoints (your OpenAPI file, or your router's table) and put each one in exactly one group:

| Group | What it means | In the route map |
|---|---|---|
| **Approved by a person** | An agent does it for someone, and that person agrees first. Most endpoints that read or change a person's data. | A line with a capability, a class and a level 1 to 3 |
| **Agent identity only** | No person is involved, but you want to know which agent calls: public catalogue, search, prices, availability. | A line with no capability, `level=0` |
| **Not for agents** | Agents never call it through AllowedBy (section 6). | Not in the map; keep your own authentication on it |

A route of the map is for agents only: a request to it without AllowedBy headers is answered `401`. Endpoints that
people's browsers or your other clients also call stay on their own paths (section 5).

## 2. Give each approved endpoint a class

The class says how serious the action is. Ask one question per endpoint: **if the agent got it wrong, what would it
take to undo?**

| Class | When | Examples | What the SDK does |
|---|---|---|---|
| `read` | Nothing changes for anyone | list orders, get an invoice, download a statement, search the person's files | An approval can be reused, for up to 30 days |
| `write` | A change the person can undo themselves | create a draft, add to a basket, edit a note, tag, archive | An approval can be reused, for up to 7 days |
| `write-hard` | Hard to undo, or someone else sees it | send a message or an email, submit an order, publish, invite a user, approve an invoice, change who has access | Your app creates the approval for this exact request, usable once, for up to 24 hours |
| `irreversible` | Cannot be undone, or has legal effect | pay, transfer, sign a contract, delete for good, close an account | Your app creates the approval for this exact request, usable once, for up to 1 hour |

- **Choose by the worst case of the endpoint, not the usual one.** `PATCH /orders/{id}` that can also cancel a shipped
  order is `write-hard`. If one endpoint does harmless and serious things, split it (section 4).
- **Money: class by amount.** One payment route can be `write-hard` up to a threshold and `irreversible` above it,
  read from the body: `cls=[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}]` with
  `amount_field="/total"`. The person can then set a limit per call, day, week, month or in total.
- **Deletion:** `write` when it goes to a bin the person can restore from, `irreversible` when it is gone.
- **Serious routes need a linked account.** A service MUST link the person to its own account before it accepts
  `write-hard` or `irreversible` approvals, and for anything several users share (ABY-3 §6). Python has
  `require_link=True`, but keeps the links in one process's memory: after a restart, or on another instance, those
  routes are refused until the person links again. The other SDKs have no linking yet. In production, build the link
  route and keep the links in your database ([account linking](https://docs.allowedby.com/guides/existing-sign-in#2-link-the-person-to-their-account)).
- **Levels follow the class.** The specs give level 2 as the default for `write-hard` and `irreversible` (ABY-3 §4), but
  `route()` defaults to `level=1` for every class: write `level=2` on those routes yourself, and go lower only with a
  reason you can write down.

## 3. Give each endpoint a level, a capability and a resource

**Level**: how sure you need to be of the person, not of the agent.

| Level | Use it for |
|---|---|
| 0 | Agent identity only (group 2). No person. |
| 1 | The person's own data and reversible actions (`read`, `write`): a passkey tap. Most routes. |
| 2 | A verified legal identity: what the specs set for `write-hard` and `irreversible` (write it: `route()` defaults to 1), and anything you would ask ID for. |
| 3 | A legal identity verified at the highest level, on a hardware passkey: high-value or legally binding acts. |

**Capability**: `namespace:action`, what the person allows, in their words. One capability per thing a person would
want to allow on its own.

- **Group by what the person decides, not by HTTP method.** `GET /invoices` and `GET /invoices/{id}` are both
  `invoices:read`. `POST /invoices/{id}/approve` and `POST /invoices/{id}/pay` are two capabilities: people allow the
  first more easily than the second.
- **Namespaces are your domains**: `orders`, `invoices`, `messages`, `files`. Keep them stable: approvals name them.
  `aby` is reserved.
- **Never one capability for everything** (`api:all`). The person would approve without knowing what for.

**Resource**: what the action acts on, built from the path: `invoice:{id}`, `project:{project}/file:{file}`. The
person approves a scope (this invoice, or every invoice: `invoice:*`), and each request must fall inside it.

- **The id must be in the path.** The resource takes `{param}` from path segments only, never from the query or the
  body. `GET /invoice?id=7` cannot be scoped to invoice 7: add `GET /invoices/{id}`.
- **A parameter is a whole segment.** `/files/{id}` works; `/files/report-{id}.pdf` does not.
- **Collections**: `GET /invoices` acts on `invoice:*`; creating one acts on a fixed name such as `invoice:new`.
- **Multi-tenant**: start the path and the resource with the tenant (`/t/{tenant}/invoices/{id}`, resource
  `{tenant}:invoice:{id}`), so an approval for one customer never works for another
  ([tenants](https://docs.allowedby.com/guides/accept-agents#8-tenants-multi-tenant-saas)).

**Sentence**: each capability has the sentence the person signs, written by you, with only the values the approval
enforces (`{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, `{count.max}`, `{fields}`). If you cannot
write a short, true sentence for an endpoint, it is doing too much.

## 4. Reshape what does not fit

Some API designs cannot be scoped or approved as they are. Add a small agent-facing route next to them instead of
weakening the check.

| Your API has | Why it does not fit | Do instead |
|---|---|---|
| **GraphQL or JSON-RPC** on one `POST /graphql` | One route, one capability, one sentence for every query and mutation | One agent route per operation the agent needs (`GET /agent/orders`, `POST /agent/orders/{id}/cancel`), calling the same resolvers |
| **Ids in the query or the body** (`?id=7`, `{"invoiceId": 7}`) | The scope cannot name the object | The id in the path |
| **Batch endpoints** (`POST /invoices/batch-approve`) | One approval for many objects, one amount | One request per object, or a batch whose scope is a named container (`run:{id}`) with `amount_field` on the total |
| **A `PATCH` that can do anything** | The class must be the worst case | Split: `PATCH /orders/{id}` for safe fields, `POST /orders/{id}/cancel` for the serious one |
| **`GET` with side effects** (`GET /unsubscribe?...`, `GET /export` that emails) | Readers approve reads | Make it a `POST` with the right class |
| **File uploads** (multipart, raw bytes) | A route of the map accepts only a JSON object body, at most 1 MiB by default (`max_body`) | An approved JSON route that returns a short-lived upload URL, outside the map, bound to that upload |
| **Forms** (`application/x-www-form-urlencoded`) | Same: JSON only | A JSON route for agents |
| **WebSockets, streaming input** | The middleware lets WebSocket connections through without any check | A JSON route per action; server-sent events or streaming responses on an approved `GET` are fine |
| **Long jobs** | The request returns before the work is done | Approve the start (`POST /exports`), then `GET /exports/{id}` as `read` |
| **Retries of serious actions** | A `write-hard` or `irreversible` approval works once: a retry after a timeout needs a new one | Make the handler idempotent: a client reference in the body, and the existing result for a repeat |

## 5. Where the middleware goes

**In your stack:**

```text
TLS / load balancer / reverse proxy      forwards Allowed-By and AllowedBy-Proof unchanged, up to 8 KiB
└─ AllowedBy middleware                  outermost layer of your app
   └─ anything that rewrites the path or the method (mounts, rewrites, method override)
      └─ your router
         └─ your handler                 reads the context: who approved, what, at which level
```

- **Outermost in your app**, before anything that changes the path or the method, and before your own
  authentication middleware: that middleware would refuse agent requests, which carry no token of yours.
- **Mounted under a prefix?** Tell the SDK where (`SCRIPT_NAME`, ASGI `root_path`, or the `prefix` argument): the agent
  signs the full URL.
- **One shared store** for the replay and single-use sets when you run more than one instance
  ([storage](https://docs.allowedby.com/guides/accept-agents#12-storage-for-replay-and-single-use-state)).
- **The SDK's own endpoints** (`/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`,
  `/allowedby/...`) must be reachable without your authentication.

**Per framework**, one line, from the [language guides](https://docs.allowedby.com/):

| Language | Where |
|---|---|
| Python | WSGI/ASGI middleware; FastAPI `install(app, aby)`; Flask extension; Django `MIDDLEWARE` |
| TypeScript / JavaScript | Node `http`, Express, Fastify, Hono, Next.js middleware, NestJS |
| Go | `net/http` handler wrapper; Gin, Echo, chi middleware |
| Java / Kotlin | Servlet filter; Spring Boot starter |
| C# / .NET | ASP.NET Core middleware |
| PHP | PSR-15 middleware; Laravel; Symfony |
| Ruby | Rack middleware; Rails; Sinatra |
| Rust | `tower` layer (axum); actix-web |

**Agents and people on the same API.** A method and path is either for agents (in the map) or for your other clients
(not in the map), never both. Serve agents on their own prefix or host (`/agent/...`, `agents.api.example.com`) with
the same handlers behind them. If your users sign in through a provider, read
[Apps that use Auth0, Okta, Cognito or another sign-in provider](https://docs.allowedby.com/guides/existing-sign-in).

**In your handlers:**

- **Own data by the person**, from the context (`human_id`, or your user after [linking](https://docs.allowedby.com/guides/existing-sign-in)),
  never by an id the agent sends.
- **Keep your own authorisation.** The approval says the person agreed; your rules still say whether that person may
  touch that object.
- **Log** the agent, its operator, the approval id and revision, with the action.

## 6. Where not to put AllowedBy

| Endpoint | Why not | Keep |
|---|---|---|
| Sign-up, login, password reset, MFA, OAuth and SSO endpoints | They create or prove your own sessions; an agent must not act there for a person | Your current flow |
| Webhooks and callbacks from other companies (payment provider, e-mail service) | The caller is a company, not an agent acting for a person | Their signatures (HMAC, mTLS) |
| Your own service-to-service calls, cron jobs, queues | No agent, no person | Your internal authentication |
| Back-office and admin tools | Staff actions, not agents | Your staff authentication |
| Health checks, metrics, status pages | No person's data | Open, or your monitoring's credentials |
| Static files, the web app itself, public pages | Nothing to approve | Untouched; your CDN |
| Public data where you do not need to know the agent | Nothing to approve | Untouched, or level 0 if you want the agent's identity and rate limits per agent |
| Endpoints that move data in bulk out of your system (full exports, admin dumps) | Too much for one sentence | A narrower agent route, or none |
| Anything not ready for an agent's mistakes | An approval does not make an agent careful | Nothing, until it is |

And never:

- **An agent route that also accepts your old token** as a fallback: it skips the person's approval.
- **Catching a refusal** from the SDK and serving the request anyway.
- **The same handler under a path outside the map** (an alias, a catch-all, `/v2/...`) that agents can reach without a
  check. The adapters refuse paths that only look like a protected route; declare your own such pages with
  `unprotected=` ([wrap your app](https://docs.allowedby.com/guides/accept-agents#5-wrap-your-app)).

## 7. A worked example

An invoicing API before and after.

| Endpoint today | Group | Class | Level | Capability | Resource |
|---|---|---|---|---|---|
| `POST /login`, `POST /oauth/token` | not for agents | | | | |
| `POST /webhooks/stripe` | not for agents | | | | |
| `GET /health` | not for agents | | | | |
| `GET /catalogue` | agent identity only | read | 0 | none | |
| `GET /invoices` | approved | read | 1 | `invoices:read` | `invoice:*` |
| `GET /invoices/{id}` | approved | read | 1 | `invoices:read` | `invoice:{id}` |
| `POST /invoices` (draft) | approved | write | 1 | `invoices:write` | `invoice:new` |
| `POST /invoices/{id}/send` | approved | write-hard | 2 | `invoices:send` | `invoice:{id}` |
| `POST /invoices/{id}/pay` | approved | by amount | 2 | `invoices:pay` | `invoice:{id}` |
| `DELETE /invoices/{id}` (bin) | approved | write | 1 | `invoices:delete` | `invoice:{id}` |
| `POST /graphql` | reshaped | | | | as the rows above |
| `POST /invoices/import` (CSV upload) | not yet | | | | |

```python
from allowedby import route

routes = [
    route("GET", "/agent/catalogue", level=0, summary="The catalogue"),
    route("GET", "/agent/invoices", "invoices:read", level=1, resource="invoice:*", summary="List your invoices"),
    route("GET", "/agent/invoices/{id}", "invoices:read", level=1, resource="invoice:{id}", summary="One invoice"),
    route("POST", "/agent/invoices", "invoices:write", cls="write", level=1, resource="invoice:new",
          summary="Create a draft invoice", body={"customer": "customer id", "lines": "the lines"}),
    route("POST", "/agent/invoices/{id}/send", "invoices:send", cls="write-hard", level=2, resource="invoice:{id}",
          require_link=True, summary="Send an invoice to its customer"),  # links in memory: see section 2
    route("POST", "/agent/invoices/{id}/pay", "invoices:pay", level=2, resource="invoice:{id}",
          cls=[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}],
          amount_field="/total", require_link=True, summary="Pay an invoice",
          body={"total": "the amount", "currency": "EUR"}),
    route("DELETE", "/agent/invoices/{id}", "invoices:delete", cls="write", level=1, resource="invoice:{id}",
          summary="Move an invoice to the bin"),
]
templates = {
    "invoices:read": "Read your invoices",
    "invoices:write": "Create draft invoices",
    "invoices:send": "Send invoice {scope} to its customer",
    "invoices:pay": "Pay {scope}, up to {amount.max} {amount.currency}",
    "invoices:delete": "Move invoice {scope} to the bin",
}
```

## 8. Roll it out

1. **Start with reads.** Map the `read` routes, try them with an agent against your staging app
   ([testing](https://docs.allowedby.com/guides/accept-agents#15-testing-with-an-agent)), watch the admin console.
2. **Then reversible writes**, then the serious routes one by one, each with its sentence reviewed by someone who has
   not seen the code.
3. **Test the refusals**: each agent route without headers answers `401`; with your old token alone, `401`; a
   variant of a protected path (`/agent/invoices/7/`, `/agent/invoices.json`) does not reach the handler.
4. **Go live** with the [going-live checklist](https://docs.allowedby.com/guides/accept-agents#14-going-live-checklist).

When you change the map later, keep capability names and resources stable: existing approvals name them. A new name
means people approve again.
