# The Data API

> Every table and view as REST, filtered, sorted, paged and joined in the URL, compatible with PostgREST's syntax.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://data.docs.sypnia.com/data/rest-api/

For agents: Data API at https://<ref>.data.sypnia.com/rest/v1 (PostgREST-compatible subset): GET /{table}?select=cols,rel(cols)&col=op.value with eq neq gt gte lt lte like ilike in is cs cd ov fts plfts phfts wfts and not./or=(…); order=col.desc.nullslast; limit/offset or Range header; Prefer: count=exact|planned|estimated → Content-Range; POST insert (bulk), Prefer return=representation, upsert with resolution=merge-duplicates + on_conflict; PATCH/DELETE need a filter; POST /rpc/{fn}; POST /transaction; GET / (OpenAPI); Accept-Profile/Content-Profile for schemas; max_rows 1000; statement_timeout 8 s (30 s service_role); schema cache refreshed on DDL.

The engine reads your schema and serves every table, view and function of the **exposed schemas** (by default `public`) at `/rest/v1`. The query language is PostgREST's, so existing clients and habits work.

## Read

```text
GET /rest/v1/orders?select=id,total,customer:customers(name)&status=eq.paid&total=gte.50000&order=created_at.desc&limit=20
```

| Part                                  | Meaning                                                                                                        |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `select=id,total`                     | columns to return                                                                                              |
| `customer:customers(name)`            | a related row through a foreign key, renamed `customer`                                                        |
| `status=eq.paid`                      | a filter: `eq neq gt gte lt lte like ilike in is cs cd ov fts plfts phfts wfts`, and `not.` before any of them |
| `or=(status.eq.paid,total.gt.100000)` | several filters joined with OR                                                                                 |
| `order=created_at.desc.nullslast`     | sorting                                                                                                        |
| `limit=20&offset=40`                  | paging; or the header `Range: 40-59`                                                                           |

Ask for a count with `Prefer: count=exact` (or `planned`, `estimated` for big tables); it comes back in `Content-Range: 40-59/1324`.

## Write

```text
POST /rest/v1/orders            body: one object or an array      Prefer: return=representation
PATCH /rest/v1/orders?id=eq.42  body: the columns to change
DELETE /rest/v1/orders?id=eq.42
```

- **Upsert**: `POST` with `Prefer: resolution=merge-duplicates` (or `ignore-duplicates`) and `?on_conflict=email`.
- `PATCH` and `DELETE` without any filter are refused: changing a whole table goes through SQL, on purpose.
- `Prefer: return=minimal` returns nothing, `return=representation` the rows as they are now.

## Functions

`POST /rest/v1/rpc/close_month` with a JSON body calls `public.close_month(...)` with named arguments. Functions are called with `POST`, whatever their volatility.

## Transactions

`POST /rest/v1/transaction` runs several operations in **one database transaction**, as the caller: row-level security applies as in any request. Use it for what must not half-happen, such as an order and its items, or a stock decrement that must not race.

```json
{"operations": [
  {"name": "stock", "method": "PATCH", "table": "products", "query": {"id": "eq.1", "left_today": "gte.2"},
   "increment": {"left_today": -2}, "expect": {"rows": 1}},
  {"name": "order", "method": "POST", "table": "orders", "body": {"note": "counter"}},
  {"method": "POST", "table": "order_items", "body": {"order_id": {"$ref": "order.id"}, "product_id": 1, "qty": 2}}
]}
```

- **Operations.** Each is `GET`, `POST`, `PATCH` or `DELETE` on a `table` (and its `schema` when it is not the default), with a PostgREST `query` (a string or an object) and a `body`. Each runs in its own savepoint. There are at most 100 per call. `returning: false` leaves an operation's rows out of the answer.
- **`increment`** (with `PATCH`) adds in the database (`col = col + n`), so concurrent decrements never lose an update.
- **`expect`** (`{rows}`, `{min}`, `{max}`) checks how many rows the operation returned or changed. When it does not hold, everything is rolled back with `409 expectation_failed`. In the example above, nobody gets the last two loaves twice.
- **`{"$ref": "order.id"}`** uses a result of an earlier operation: its `name` or index, then optionally a row number (`items.2.id`), then a field.
- **`on_error: "continue"`** rolls back only that operation. By default, any error rolls back all of them, and the error names the operation.
- **The answer** is `{"results": [{"op", "name", "count", "rows"}…]}`; an operation that failed with `on_error: "continue"` comes back as `{"op", "name", "error"}`.

`transaction` is reserved like `rpc`: a table with that name is not reachable at `/rest/v1/transaction`. From the SDK, call `sypnia.transaction([...])`. Sypnorm, in Sypnia Cases, runs atomic use cases on it with [`createRunner(client, { atomic: true })`](https://cases.docs.sypnia.com/sypnorm/runners/), for cases no other case listens to. A case some case listens to never runs here: the app calls `POST /_cases/<id>` on its area's service, with the person's session and under row-level security, and the service writes the event to its outbox in the same database transaction as the case's rows. The Data API runner refuses such a case.

## The API description

`GET /rest/v1/` returns an **OpenAPI 3.1** document of the project's Data API: every exposed table and view with its columns, keys and functions, built from the schema cache. It needs a signed-in user, a PAT, a machine token or a secret key; a publishable key alone gets `401`.

## Scopes

A PAT or an OAuth client token reaches the Data API with `data:read` for reads, or `data:write` for both. A token with only other standard scopes (say only `sql:read`) gets `403 insufficient_scope` instead of an empty list. Tokens with a project's own scopes go on, and your policies decide with `sypnia.scopes()`.

## Schemas

Expose more schemas in the project settings; pick one per request with `Accept-Profile: billing` (reads) or `Content-Profile: billing` (writes).

## Limits

|                   | Default                                                     |
| ----------------- | ----------------------------------------------------------- |
| Rows per response | 1 000 (`SYPNIA_DATA_MAX_ROWS` when self-hosted)             |
| Statement time    | 8 s for `anon` and `authenticated`, 30 s for `service_role` |
| Request body      | 2 MB                                                        |

## The schema cache

The engine keeps a description of your schema in memory. It is refreshed when a migration runs through the engine, when any DDL happens (an event trigger sends `NOTIFY sypnia_data, 'reload schema'`) and every 60 seconds.
