---
name: rebase-api
description: Guide for working with Rebase's auto-generated REST API. Use this skill when the user needs to understand the API endpoints, query parameters, filtering, sorting, or pagination.
---

# Rebase Auto-Generated APIs

> **WARNING FOR AGENTS**: If you are writing a script or data task, **default to using the Rebase SDK** (`@rebasepro/client` or `@rebasepro/server`) instead of making raw REST API calls (`fetch` / `curl`). For custom backend functions, use `client.functions.invoke('function-name', payload)` — **NEVER** manually construct `/api/functions/` URLs or extract tokens from localStorage. Only use raw API calls if specifically instructed to do so or if you are demonstrating HTTP usage to the user.

Every table declared in `backend/schema` automatically gets full REST CRUD endpoints. No manual route creation needed.

## REST API

### Base Paths

All data routes are mounted under `/api/data/`. Other route categories:

| Base Path | Purpose |
|-----------|---------|
| `/api/data/{slug}` | Table CRUD (auto-generated from `backend/schema`) |
| `/api/data/{slug}/count` | Count matching entities |
| `/api/data/{slug}/aggregate` | count/sum/avg/min/max, optionally grouped |
| `/api/data/{parent}/{parentId}/{relation}` | Nested relation routes |
| `/api/auth/*` | Authentication (login, register, refresh, OAuth) |
| `/api/admin/*` | Admin surfaces (users, roles, keys, cron, backups, logs, schema), each behind its own admin-plane scope |
| `/api/admin/api-keys` | Service API key management (`keys:read` / `keys:write`) |
| `/api/auth/keys` | The caller's own personal API keys (when `auth.personalKeys` is on) |
| `/api/auth/scopes` | Every scope the backend knows, and the ones the caller holds |
| `/api/storage/*` | File uploads and downloads |
| `/api/functions/{name}` | Custom backend functions |
| `/api/admin/schema-editor/*` | Visual schema editor (dev only; `/api/schema-editor/*` is a deprecated alias) |
| `/api/docs` | OpenAPI 3.0.3 JSON spec — by default for the callers `GET /api/schema/tables` describes tables to, each the tables they may see; everyone with `enableSwagger: true`; admins with `false` |
| `/api/swagger` | Swagger UI — only with `enableSwagger: true` (`REBASE_ENABLE_SWAGGER=true`), never in production |
| `/api/health` | Health check |
| `/api/schema/tables` | The tables this backend serves, as `TableDescriptor[]` redacted for the caller (`/api/schema/tables/{slug}` for one) — what the CMS, Studio and MCP read |
| `/api/meta/contract` | Schema contract, for remote SDK generation (needs `schema:read`) |
| `/api/meta/schema-version` | The schema hash this backend was built from (unauthenticated) |

### CRUD Operations

> **IMPORTANT FOR AGENTS:** Updates use `PATCH` — a partial write, only the properties you send. `PUT` still reaches the same handler, so it is a partial write too rather than the replace its verb implies, and it answers with a `Deprecation: true` header — write `PATCH`. `POST` returns `201`, `DELETE` returns `204` (empty body).

| Method | Endpoint | Description | Status |
|--------|----------|-------------|--------|
| `GET` | `/api/data/{slug}` | List entities (with filtering, sorting, pagination) | `200` |
| `GET` | `/api/data/{slug}/count` | Count matching entities (with optional filters) | `200` |
| `GET` | `/api/data/{slug}/aggregate` | Aggregate over matching entities | `200` |
| `GET` | `/api/data/{slug}/:id` | Get a single entity by ID | `200` |
| `POST` | `/api/data/{slug}` | Create a new entity | `201` |
| `PATCH` | `/api/data/{slug}/:id` | Update a record — partial, only what you send | `200` |
| `DELETE` | `/api/data/{slug}/:id` | Delete a record | `204` |
| `POST` | `/api/data/{slug}/query` | The list, its query parameters in a JSON body (a read) | `200` |
| `POST` | `/api/data/{slug}/count` | The count, its query parameters in a JSON body (a read) | `200` |
| `POST` | `/api/data/{slug}/bulk` | Create many in one transaction | `200` |
| `PATCH` | `/api/data/{slug}/bulk` | Update many in one transaction | `200` |
| `POST` | `/api/data/{slug}/bulk/delete` | Delete many in one transaction | `200` |
| `POST` | `/api/data/_batch` | Write across tables in one transaction | `200` |

### Nested Relation Routes

For tables with relations, Rebase generates nested routes automatically. The URL pattern is `/{parent}/{parentId}/{child}`, and it supports arbitrarily deep nesting (parent/id/child/id/grandchild):

| Method | Endpoint | Description | Status |
|--------|----------|-------------|--------|
| `GET` | `/api/data/{parent}/{parentId}/{child}` | List child entities | `200` |
| `GET` | `/api/data/{parent}/{parentId}/{child}/count` | Count child entities | `200` |
| `GET` | `/api/data/{parent}/{parentId}/{child}/:id` | Get a single child entity | `200` |
| `POST` | `/api/data/{parent}/{parentId}/{child}` | Create a child entity | `201` |
| `PATCH` | `/api/data/{parent}/{parentId}/{child}/:id` | Update a child entity | `200` |
| `DELETE` | `/api/data/{parent}/{parentId}/{child}/:id` | Delete a child entity | `204` |

**Example:** List all posts by author `111094`:
```bash
GET /api/data/authors/111094/posts
```

## Query Parameters

### Pagination

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `limit` | integer | `50` | Max results per page (max: `1000`; a larger one is a 400, not a clamp) |
| `offset` | integer | `0` | Number of records to skip |
| `page` | integer | — | Page number (alternative to offset). Calculates offset as `(page - 1) * limit` |

> **IMPORTANT FOR AGENTS:** The default limit is **50** (`DEFAULT_LIST_LIMIT`) and the
> ceiling is **1000** (`MAX_LIST_LIMIT`). Asking for more is a 400 naming the parameter,
> not a silent clamp — so a client that assumes it got everything is told otherwise.

### Sorting

Use the `orderBy` parameter. Two formats are supported:

**Simple format:**
```
?orderBy=field:direction
```

**JSON array format (for multi-column sort):**
```
?orderBy=[{"field":"createdAt","direction":"desc"},{"field":"name","direction":"asc"}]
```

The keys apply in the order given: the second decides between rows the first
calls equal. `direction` may be omitted and defaults to `asc`.

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `orderBy` | string | Sort field and direction | `?orderBy=createdAt:desc` |

What an agent has to know before constructing one:

- **A repeated `?orderBy=` is not a multi-key sort.** The last value wins, as
  for every query parameter. Use the JSON array.
- **The whole shape is validated.** A bare object (`?orderBy={"field":"name"}`),
  a bare `["name"]`, a number, or a direction that is not `asc`/`desc` is a
  **400**, not a 200 with unsorted rows. So is a field the table does not
  have (`UNKNOWN_ORDER_BY_FIELD`), and a to-many relation, which has no single
  value per row to order by (`ORDER_BY_FIELD_NOT_SORTABLE`).
- **Every sort ends on the row id descending**, whether asked for or not. That
  is what makes the ordering total; paging with `offset` over an order that is
  not total repeats some rows and skips others.
- Both spellings work on nested routes too — `/api/data/authors/:id/posts`.

### Filtering (PostgREST-Style)

> **IMPORTANT FOR AGENTS:** Filters use PostgREST-style syntax: `?field=op.value`. This is NOT bracket syntax. For example: `?status=eq.active`, NOT `?filter[status][eq]=active`.

Every column of the table can be used as a query parameter with an operator prefix:

```
?{field}={operator}.{value}
```

**Implicit equality:** A plain value without an operator prefix implies equality:
```
?status=active          →  status == "active"
?price=29.99            →  price == 29.99
```

### Filter Operators

| Operator | Mapped To | Description | Example |
|----------|-----------|-------------|---------|
| `eq` | `==` | Equal | `?status=eq.active` |
| `neq` | `!=` | Not equal | `?status=neq.archived` |
| `gt` | `>` | Greater than | `?price=gt.50` |
| `gte` | `>=` | Greater than or equal | `?price=gte.50` |
| `lt` | `<` | Less than | `?price=lt.100` |
| `lte` | `<=` | Less than or equal | `?price=lte.100` |
| `in` | `in` | Value in list | `?status=in.(active,published)` |
| `nin` | `not-in` | Value not in list | `?status=nin.(archived,deleted)` |
| `cs` | `array-contains` | Array contains value | `?tags=cs.javascript` |
| `csa` | `array-contains-any` | Array contains any of values | `?tags=csa.(javascript,typescript)` |
| `like` / `ilike` | `like` / `ilike` | SQL `LIKE` / `ILIKE` | `?name=ilike.%25widget%25` |
| `nlike` / `nilike` | `not-like` / `not-ilike` | Negated `LIKE` / `ILIKE` | `?name=nilike.test%25` |
| `isnull` | `is-null` | Is null | `?deletedAt=isnull.null` |
| `notnull` | `is-not-null` | Is not null | `?deletedAt=notnull.null` |

> **IMPORTANT FOR AGENTS:** `like`, `ilike`, `nlike` and `nilike` are real operators — SQL `LIKE`/`ILIKE` with `%` and `_` wildcards. They are the wrong tool for prose: they cannot use a text index, so a leading `%` scans the table. For searching text, use `searchString`, and read the Text Search section below before telling a user what it will match, because by default it does not see inside JSONB.

**Array values** for `in`, `nin`, and `csa` use parenthesized comma-separated lists: `(val1,val2,val3)`.

**Type coercion:** Querystring values are not parsed on the way in — they reach the driver as strings and are compared against the column's type. `?field=eq.null` is the four-character string `"null"`; test for null with `isnull` / `notnull`. The JSON `?where=` dialect carries real types.

### Logical Operators (or / and)

For complex conditions, use the `or` and `and` query parameters with nested condition strings:

```
?or=(status.eq.active,status.eq.pending)
?and=(price.gte.10,price.lte.100)
```

Nested logical conditions are also supported:

```
?or=(status.eq.active,and(price.gte.10,price.lte.50))
```

### Text Search

| Parameter | Type | Description |
|-----------|------|-------------|
| `searchString` | string | Text search. Substring by default; ranked full-text if the table declares a `search` block |

```
?searchString=widget
```

By default this is `ILIKE '%widget%'` OR-ed across the table's top-level
text columns (not enum or uuid ones); with several words, each word must
match some column. It does **not** reach inside JSONB or array
columns, and does not rank. A table that declares a `search` block gets
ranked full-text matching over the fields it names, and rows carry a `_score`
that `orderBy` accepts:

```
?searchString=auditor%20iso%2014001&orderBy=_score:desc
```

`orderBy=_score` returns 400 on a table without the block, or without a
`searchString`.

### Vector Search

Nearest-neighbour search over a property of type `vector`. All four parameters
below work together; `vector_search` and `vector` are both required.

| Parameter | Type | Description |
|-----------|------|-------------|
| `vector_search` | string | Name of the `vector` property |
| `vector` | JSON array | Query embedding, e.g. `[0.12,-0.04,0.98]`. Length must match the property's `dimensions` |
| `vector_distance` | string | `cosine` (default), `l2`, or `inner_product` |
| `vector_threshold` | number | Drop rows farther than this |

```
?vector_search=embedding&vector=%5B0.12%2C-0.04%5D&vector_threshold=0.35
```

Rows come back closest-first, each with a `_distance`. Other filters apply
before the ordering. Without `?limit`, a vector search returns 10 rows
(`DEFAULT_VECTOR_LIST_LIMIT`), not 50.

### Relation Includes (Eager Loading)

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `include` | string | Comma-separated list of relations to eager-load | `?include=author,tags` |

Use `*` to include all relations:
```
?include=*
```

### Field Selection

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `fields` | string | Comma-separated list of fields to return | `?fields=id,name,price` |

### Reserved Query Keys

These parameter names are reserved and will NOT be interpreted as filter fields:

`limit`, `offset`, `page`, `after`, `orderBy`, `include`, `fields`, `distinct`, `count`, `searchString`, `searchExplain`, `vector_search`, `vector`, `vector_distance`, `vector_threshold`, `or`, `and`, `not`, `where`, `select`, `groupBy`, `deleted`, `hard`

## Response Format

### List Response (GET table)

```json
{
  "data": [
    { "id": "uuid-1", "name": "Product A", "price": 29.99 },
    { "id": "uuid-2", "name": "Product B", "price": 49.99 }
  ],
  "meta": {
    "total": 150,
    "limit": 20,
    "offset": 0,
    "hasMore": true
  }
}
```

> **IMPORTANT FOR AGENTS:** The pagination envelope key is `meta`, NOT `pagination`.

### Single Entity Response (GET by ID)

Returns the flat entity object directly (no `data` wrapper):

```json
{
  "id": "uuid-1",
  "name": "Product A",
  "price": 29.99,
  "createdAt": "2025-01-15T10:30:00.000Z"
}
```

### Create Response (POST — 201)

Returns the created entity as a flat object:

```json
{
  "id": "generated-uuid",
  "name": "New Product",
  "price": 19.99
}
```

### Update Response (PATCH — 200)

Returns the updated entity as a flat object.

### Delete Response (DELETE — 204)

Returns an empty body with status `204 No Content`.

### Count Response

```json
{
  "count": 42
}
```

## Error Handling

All errors follow the canonical shape:

```json
{
  "error": {
    "message": "Human-readable error description",
    "code": "ERROR_CODE",
    "details": {}
  }
}
```

The `details` field is optional and only present when additional context is available.

### Error Codes and HTTP Status Codes

| HTTP Status | Code | Description |
|-------------|------|-------------|
| `400` | `BAD_REQUEST` | Invalid input or malformed request |
| `400` | `INVALID_INPUT` | Validation failure |
| `401` | `UNAUTHORIZED` | Missing or invalid authentication token |
| `401` | `INVALID_CREDENTIALS` | Wrong email/password |
| `401` | `INVALID_TOKEN` | Unknown refresh token, or provider credentials an OAuth sign-in could not verify (an invalid or expired access token is `401 UNAUTHORIZED`; a bad reset, verification or magic-link token is `400 INVALID_TOKEN`) |
| `403` | `FORBIDDEN` | Insufficient permissions |
| `403` | `SCOPE_MISSING` | The credential lacks the scope this route needs; `details.requiredScope` names it (e.g. `data:write:orders`) |
| `404` | `NOT_FOUND` | Entity not found |
| `409` | `CONFLICT` | Duplicate resource (e.g., email exists) |
| `409` | `EMAIL_EXISTS` | Registration with existing email |
| `413` | `PAYLOAD_TOO_LARGE` | Request body exceeds max size (default 10MB) |
| `500` | `INTERNAL_ERROR` | Unexpected server error |
| `503` | `SERVICE_UNAVAILABLE` | A service the request depends on could not be reached: an S3/MinIO bucket, or a host a function `fetch()`es (0.25+; on 0.24 a `500` whose code is the socket error, such as `ECONNREFUSED`, or `INTERNAL_ERROR`). The host is in the server log only |
| `503` | `DATABASE_UNAVAILABLE` | The database could not be reached (0.25+). Sent with `Retry-After: 5`, by every route and the realtime socket |

### ApiError Factory Methods

The backend uses `ApiError` static methods to throw typed errors:

```typescript
ApiError.badRequest("Invalid email format", "INVALID_INPUT");
ApiError.unauthorized("Token expired");
ApiError.forbidden("Admin access required");
ApiError.notFound("Entity not found");
ApiError.conflict("Email already registered", "EMAIL_EXISTS");
ApiError.internal("Database connection failed");
ApiError.serviceUnavailable("Service is down");
```

From 0.25, a route that catches a database error itself answers an outage the
way the built-in routes do with `isDatabaseUnreachable` and
`ApiError.databaseUnavailable()`, both from `@rebasepro/server`:

```typescript
import { ApiError, isDatabaseUnreachable, rebase } from "@rebasepro/server";

export async function countOrders() {
    try {
        return await rebase.sql("SELECT count(*) FROM orders");
    } catch (error) {
        if (isDatabaseUnreachable(error)) throw ApiError.databaseUnavailable(); // 503 + Retry-After
        throw error;
    }
}
```

## Authentication

### Bearer Token (JWT)

```
Authorization: Bearer <jwt-token>
```

### No query-parameter token

Data, auth, functions and admin routes read the credential from the
`Authorization` header only — a `?token=` on `/api/data/...` is not a
credential (it is parsed as a filter on a field named `token`). The one
exception is storage file serving (`/api/storage/file/*`, `/api/storage/metadata/*`),
which accepts a scoped download `?token=` for `<img src>`-style links.

### Service Key

A static secret key for server-to-server or script authentication. When a request sends a Bearer token matching the service key, it is granted admin-level access (`uid: "service"`, `roles: ["admin"]`) without JWT verification.

```
Authorization: Bearer <service-key>
```

### API Keys (rk_ prefix)

API keys start with the `rk_` prefix and are validated against the database. What a key may do is a list of **scopes**, `resource:action[:target]`:

```
Authorization: Bearer rk_live_abc123...
```

- `data:read`, `data:write`, `data:delete` — plain for every table, or narrowed: `data:read:orders`. The operation comes from the HTTP method (`GET` → read, `POST`/`PUT`/`PATCH` → write, `DELETE` → delete; `POST /bulk/delete` is a delete, `POST /query` and `POST /count` are reads). On a nested path the target collection needs the operation and each parent `data:read`.
- `storage:read`, `storage:write`, `storage:delete` — target is a storage source id; the default source is `(default)`.
- `functions:invoke` — or `functions:invoke:<name>` for one function.
- Admin-plane scopes (`users:read`, `cron:write`, `logs:read`, `schema:read`, …) reach that admin surface. `keys:read`/`keys:write` can never go on a key.

A missing scope answers `403 SCOPE_MISSING` with `details.requiredScope`. API keys do NOT bypass RLS: a **service key** runs as `uid: "api-key:<id>"` with roles `["service", ...key.roles]`, so it only sees rows a security rule grants to `service` (or to `admin`, when the key was given `roles: ["admin"]`). A **personal key** runs as its owner. See the `rebase-auth` skill for both kinds and the minting rules.

```bash
# CLI: a scoped key
rebase api-keys create --name "Order sync" --scopes data:read:orders,data:write:orders --expires-in 30

# CLI: CI / migrations — every scope you hold (less keys:*), plus the admin RLS role
rebase api-keys create --name "CI" --full-access --roles admin

# REST
POST /api/admin/api-keys
{ "name": "Order sync", "scopes": ["data:read:orders", "data:write:orders"] }
```

### Authentication Enforcement

- **Default:** Auth is required (`requireAuth: true`). Requests without a valid token receive `401`.
- **Public access:** Set `requireAuth: false` to allow anonymous access. Access control is then fully delegated to Postgres Row-Level Security (RLS) policies.
- **Fail-closed:** The raw unscoped driver is never placed in the request context. Every request is either RLS-scoped or rejected.

## Table hooks

<!-- docs-verify: ignore -->

There is no `hooks.data` block and no `BackendHooks` type. Server-side logic on
a table's rows is a **table hook**: the `hooks` of a `defineTable`, or, for
**every** table, `export const hooks` from `backend/hooks.ts` (the top-level
`hooks` option of an ejected `initializeRebaseBackend`). Both are the same
`TableHooks` type — one concept, one signature, applied at two scopes.

```typescript
// backend/hooks.ts
import type { TableHooks } from "@rebasepro/server/schema";

export const hooks: TableHooks = {
    afterRead({ values, context }) {
        if (!context.user?.roles?.includes("admin") && values.email) {
            return { ...values, email: "***" };
        }
        return values;
    },
    beforeSave({ values, context }) {
        return { ...values, updatedBy: context.user?.uid };
    }
};
```

| Hook | Trigger | Can modify? | Can abort? |
|----------|---------|-------------|------------|
| `beforeQuery({ operation, query, context, … })` | Before every read | Return a narrowing to AND in | No (it narrows) |
| `afterRead({ values, context, … })` | Every row leaving the server | Return the transformed row | No |
| `beforeSave({ values, status, context, … })` | Before every write | Return modified values | Throw → `400 CALLBACK_REJECTED` |
| `afterSave({ id, values, context, … })` | After the write, before the commit | No | Throw → write rolled back, `400 CALLBACK_REJECTED` |
| `afterSaveError({ values, error, context, … })` | After a failed write | No | No |
| `beforeDelete({ values, id, context, … })` | Before every delete | No | Return `false` or throw |
| `afterDelete({ values, id, context, … })` | After the delete, before the commit | No | Throw → delete rolled back, `400 CALLBACK_REJECTED` |

Every hook takes **one props object**, not positional arguments. Common
fields: `table` (the descriptor), `path`, `values`, `id`, `previousValues`,
`status` (`"new" | "existing" | "copy"`) and `context`. `context.user` carries
`uid` and `roles`; an unauthenticated request arrives as
`{ uid: "anonymous", roles: ["anon"] }`, not as `undefined` — test it with
`isAnonymousUid` from `@rebasepro/types`.

> **IMPORTANT FOR AGENTS:** these are not an API-boundary interceptor. They live
> in the driver, so they fire on *every* data path — REST, WebSocket/realtime,
> MCP and server-side `rebase.dataAsAdmin` — which is what makes `afterRead` safe
> to rely on for redaction. Global hooks run first, then the table's own, then
> its columns' `.transform()`.

See the **rebase-security** skill for where they sit beside row-level security,
the **rebase-tables** skill for writing them, and
`packages/types/src/schema/hooks.ts` for the types.

## REST API Examples

`$TOKEN` in these examples is an access token — the `accessToken` a sign-in
returns, or an API key. Nothing sets it for you.

### List with filtering, sorting, and pagination

```bash
curl -H "Authorization: Bearer $TOKEN" \
  "https://example.com/api/data/products?status=eq.active&price=gte.50&orderBy=createdAt:desc&limit=10&offset=0&include=category"
```

### Create a record

```bash
curl -X POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "New Widget", "price": 19.99, "status": "draft"}' \
  "https://example.com/api/data/products"
```

### Update a record

```bash
curl -X PATCH \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "Updated Widget", "price": 24.99, "status": "active"}' \
  "https://example.com/api/data/products/uuid-123"
```

### Delete a record

```bash
curl -X DELETE \
  -H "Authorization: Bearer $TOKEN" \
  "https://example.com/api/data/products/uuid-123"
```

### Count with filters

```bash
curl -H "Authorization: Bearer $TOKEN" \
  "https://example.com/api/data/products/count?status=eq.active"
```

### Aggregates

`count`, `sum`, `avg`, `min` and `max` over the rows a filter selects, without
fetching them. Takes the same filters as the list endpoint.

```bash
curl -H "Authorization: Bearer $TOKEN" \
  "https://example.com/api/data/orders/aggregate?select=count(),sum(total)&status=eq.paid"
```

```json
{ "data": [{ "count": 96, "sum_total": 31200 }] }
```

Add `groupBy` for one row per value:

```bash
curl -H "Authorization: Bearer $TOKEN" \
  "https://example.com/api/data/orders/aggregate?select=count(),sum(total)&groupBy=status"
```

Results are keyed by function and field — `count()` becomes `count`,
`sum(total)` becomes `sum_total`.

**Row-level security applies to the rows being aggregated.** An aggregate is an
efficient way to learn about rows you cannot read, so it runs under the caller's
own policies: someone who can select nothing counts nothing. A driver that does
not implement aggregates answers **501** rather than an empty result — a
dashboard should not be told "no matches" when the truth is "not supported".

### Logical OR filtering

```bash
curl -H "Authorization: Bearer $TOKEN" \
  "https://example.com/api/data/products?or=(status.eq.active,status.eq.pending)"
```

### Nested relation listing

```bash
curl -H "Authorization: Bearer $TOKEN" \
  "https://example.com/api/data/authors/111094/posts?orderBy=createdAt:desc&limit=5"
```

## OpenAPI / Swagger

### OpenAPI 3.0.3 Spec

Available at `GET /api/docs`. Returns a JSON OpenAPI specification of the data API. It does not cover the auth, storage, functions or admin routes. Who gets it follows `enableSwagger` (`REBASE_ENABLE_SWAGGER`): unset (the default, every environment) — the callers the schema endpoint describes tables to, each a document of exactly the tables, columns and relations `GET /api/schema/tables` describes to them (401 anonymous unless `schemaTables.public`; `404 DOCS_UNAVAILABLE` with no auth configured); `true` — the whole document to everyone; `false` — the admin gate.

The spec includes:
- All table CRUD, bulk and `_batch` routes with parameters and schemas
- PostgREST-style filter parameters per field
- Nested routes for relations
- Component schemas for each table (output and input)
- `PaginationMeta` and `ErrorResponse` component schemas
- The `bearerAuth` security scheme when auth is enabled (no query-token scheme)
- Proper `201` for POST and `204` for DELETE

### Swagger UI

Available at `GET /api/swagger` only when `enableSwagger` is `true` (`REBASE_ENABLE_SWAGGER=true`) and `NODE_ENV` is not `production`. Renders an interactive Swagger UI that loads the spec from `/api/docs`.

## Metadata Endpoints

### Health Check

```
GET /health        # what an orchestrator probes
GET /api/health    # the same answer, under basePath
```

```json
{
  "status": "ok",
  "latencyMs": 3
}
```

`status` is `"ok"` with HTTP 200, or `"degraded"` with HTTP **503**. Outside production a `details` object is included when the driver supplies one; a `dataSources` array lists any secondary source that failed its probe (in production, only its `key`).

Both paths are registered by the bundle boot path (`packages/server/src/boot/boot.ts`), not by `initializeRebaseBackend` — an orchestrator probes `/health`, so it cannot live under `basePath` alone.

`GET /livez` answers `{ "status": "ok" }` without touching the database. Use `/livez` for liveness and `/health` for readiness: a database blip should not make an orchestrator kill an otherwise healthy process.

### Table descriptors and the contract

There is no `GET /api/collections`. What the backend serves is described by two endpoints:

```
GET /api/schema/tables
GET /api/schema/tables/{slug}
```

A JSON array of `TableDescriptor` (one for `/{slug}`): columns with their types, nullability and validation, relations resolved to slugs, and the `rls` posture — redacted to what this caller may know. Signed-in callers and credentials holding `schema:read` or a `data:*` scope; `404 TABLE_NOT_FOUND` for a slug this caller is not served, `404 SCHEMA_UNAVAILABLE` when no authentication is configured. It carries an `ETag`, so `If-None-Match` gets a `304`. This is what the CMS, the Studio and the MCP tools render from.

The contract endpoint is what a remotely generated SDK is built from:

```
GET /api/meta/contract
```

Gated — needs `schema:read`: an admin, the service key, or an API key holding it. With no auth configured it is not served at all (`404 CONTRACT_UNAVAILABLE`).

```json
{
  "schemaVersion": "a1b2c3…",
  "runtime": { "version": "0.34.2", "contract": 1 },
  "tables": [ "…TableDescriptor[], as GET /api/schema/tables serves an administrator…" ]
}
```

```
GET /api/meta/schema-version
```

Unauthenticated and deliberately tiny — `{ "schemaVersion": "a1b2c3…", "runtime": { "version": "0.25.1", "contract": 1 } }`. Use it in CI to tell whether a generated SDK is stale without holding admin credentials. Both responses also carry the value in an `x-rebase-schema` header.


## Server Configuration (RebaseBackendConfig)

The backend is configured by the object passed to `initializeRebaseBackend(config)`. The type is **`RebaseBackendConfig`**, defined in `packages/server/src/init.ts`: the backend's options, **`RebaseBackendOptions`** (`packages/server/src/backend/options.ts`), plus `app`, `server` and `basePath`. There is no `ApiConfig` type.

`createRebaseBackend(options)` (new in 0.25) takes `RebaseBackendOptions` itself, with a required `provision`, and mounts nothing: the routes this skill describes are then `backend.mount(app, { basePath })` — the same layout — or one group at a time, at any path, with `app.route("/v2/data", backend.routes.data())` (`routes.auth()`, `data()`, `storage()`, `functions()`, `admin()`, `cron()`, `meta()`). Every path below assumes the default `/api` base path.

> A scaffolded project does not build this object itself. `rebase dev` and the published runtime boot from the bundle: the tables come from `backend/schema/index.ts`, `storageAuthorize` from `backend/storage.ts`, global hooks from `backend/hooks.ts`, and everything else from environment variables. Pass this object directly only when embedding Rebase in a server you own.

Every option, with its default and what the runtime fills it from, is in the **`rebase-basics`** skill: `../rebase-basics/references/backend-configuration.md`. The points that matter for the API:

- **`requireAuth`, `jwtSecret`, `serviceKey`, `allowRegistration`, OAuth providers and `email` live inside `auth`**, not at the top level.
- **Storage refuses to boot in production** unless `storageAuthorize`, `storagePolicies`, `storagePublicRead` or `storageInsecureAllowAnyAuthenticated` is set.
- **`rateLimit` is on by default**, with loose per-caller limits (API key by id, user by uid, everyone else by IP), counted in-process unless you supply a `store` or set `REBASE_RATE_LIMIT_STORE=sql`.
- **CORS itself is not a config key.** It is set from the `CORS_ORIGINS` and `FRONTEND_URL` environment variables, and a production boot fails if neither is set.

### Pagination is not configurable

There is no `pagination` option. List bounds are constants in `@rebasepro/types`:

| Constant | Value | Meaning |
|----------|-------|---------|
| `DEFAULT_LIST_LIMIT` | `50` | Page size when the client sends no `?limit` |
| `MAX_LIST_LIMIT` | `1000` | Largest `?limit` a client may ask for |
| `DEFAULT_VECTOR_LIST_LIMIT` | `10` | Default for a vector search |

A `?limit` above the maximum is a **400, not a clamp** — the request is rejected rather than quietly returning fewer rows than asked for.


## References

- **Documentation:** [rebase.pro/docs](https://rebase.pro/docs)
- **GitHub:** [github.com/rebasepro/rebase](https://github.com/rebasepro/rebase)
- **REST API Generator:** `packages/server/src/api/rest/api-generator.ts`
- **Query Parser:** `packages/server/src/api/rest/query-parser.ts`
- **OpenAPI Generator:** `packages/server/src/api/openapi-generator.ts`
- **Error Handling:** `packages/server/src/api/errors.ts`
- **Server Setup:** `packages/server/src/init.ts` (`initializeRebaseBackend`, `RebaseBackendConfig`) and `packages/server/src/backend/create-backend.ts` (`createRebaseBackend`, `routes`, `mount`)
- **Backend options:** `packages/server/src/backend/options.ts` (`RebaseBackendOptions`)
- **Bundle boot (health, CORS, static apps):** `packages/server/src/boot/boot.ts`
- **API Types:** `packages/server/src/api/types.ts`
- **Auth Middleware:** `packages/server/src/auth/middleware.ts`
- **Hook Types:** `packages/types/src/schema/hooks.ts`
- **Table descriptors:** `packages/types/src/schema/descriptor.ts`, served by `packages/server/src/api/schema-tables-routes.ts`
