You write the data, not the protocol
Declare your collections and write list and get. Discovery, reserved parameters, cursors, problem+json, Merge Patch, ETags and Idempotency-Key come with it.
Tools · Build an API · v0.2.0
restep-serverThe hard part, doneDiscovery, filters, sort, cursors, problem+json errors, ETags, Idempotency-Key, caching and oauth. You write the data access; it passes restep-check --writes.
Node 18 or later · npm install restep-server
Declare your collections and write list and get. Discovery, reserved parameters, cursors, problem+json, Merge Patch, ETags and Idempotency-Key come with it.
Its example API gives 0 failed · 0 warnings in restep-check --writes 0.8.0, for draft 6: 315 checks passed over 686 requests.
fetch doesThe core speaks Request and Response. Thin adapters for Node’s http, Express and Hono; Cloudflare Workers, Deno and Bun need none.
Node 18 or later. npm install restep-server, import it, read it: it is one module of about 1,200 lines with comments pointing at the specification. For PostgreSQL, restep-server/pg, with no dependencies either.
createRestep(options) checks your configuration at start-up and returns handle(request) => Promise<Response>. For each request:
404 goes before a 405, and both before a bad parameter, in the order of 5.4.oauth or your own authenticate, and the language of its texts from Accept-Language.unsupported_parameter, a wrong value with invalid_parameter, both naming the parameter."18.50" stays an exact decimal, in brings a list), the sort always ending in id and the cursor your adapter returned last time, verified.validate, applies Merge Patch, and checks If-Match and the write atomically: within the process on its own, and across processes with createTransaction and an adapter that locks the item, such as the PostgreSQL one.ETag, Cache-Control, Cache-Groups and, for errors, application/problem+json.The cursor is whatever your list returned in next (an offset, a key, any JSON). The library signs it with HMAC and binds it to the collection, the filters, the sort and the principal, so your adapter never sees a tampered cursor or one from another query.
npm install restep-server
Node 18 or later, and nothing else: the package has no dependencies. A whole API in one file:
// server.mjs
import { createServer } from 'node:http';
import { createRestep, memoryAdapter, toNodeListener } from 'restep-server';
const api = createRestep({
collections: {
books: {
fields: {
title: { type: 'string', required: true },
price: { type: 'decimal', required: true },
category: { type: 'enum', values: ['crime', 'poetry'] },
},
filter: { price: ['lt', 'ge'], category: ['eq', 'in'] },
sort: ['title', 'price'],
count: 'exact',
data: memoryAdapter([{ id: '7', title: 'The Portugalete fog', price: '18.50', category: 'crime' }]),
},
},
});
createServer(toNodeListener(api)).listen(8080);
node server.mjs, and there is a discovery document at /, GET /books with filters, sort, fields, limit, cursors and count, and POST /books, GET, PATCH and DELETE /books/7 with validation, ETag, If-Match and Idempotency-Key. The discovery document declares "restep": "1.0-draft.6", and the profiles it announces follow from what you give it: core, query and cache always, and writes as soon as one adapter can create, update or delete.
These answers come from the library’s own example: a bookshop whose books collection has decimals, dates, durations, a boolean and an enum, and declares filters on most of them, with maxLimit: 50. Use curl -g, or curl takes the square brackets for a pattern.
$ curl -gi 'localhost:8080/books?filter[category]=novela-negra&sort=-price&fields=title,price&limit=2&count=true'
HTTP/1.1 200 OK
cache-control: no-cache
cache-groups: "/books", "/books/7", "/books/12"
content-type: application/json
etag: "bc73a0d3fdc4f64c1606505749ec24ae"
link: <https://w3id.org/restep/1/>; rel="profile"
{"items":[{"id":"7","title":"La niebla de Portugalete","price":"18.50","_etag":"\"12736708da08d3a73c57aa5450d106ab\""},
{"id":"12","title":"El último ferry","price":"16.90","_etag":"\"1b71a0b152bbe304023686c07f8ec6e6\""}],
"next":"/books?filter%5Bcategory%5D=novela-negra&sort=-price&fields=title%2Cprice&limit=2&count=true&cursor=eyJjIjoyLCJxIjoiMWE0…",
"total":3}
$ curl -g 'localhost:8080/books?limit=51'
{"type":"https://w3id.org/restep/1/errors#invalid_parameter","title":"Bad request","status":400,
"code":"invalid_parameter","detail":"Between 1 and 50.","parameter":"limit"}
$ curl -g 'localhost:8080/books?filter[reading_time][le]=P1Y'
{…,"code":"invalid_parameter","detail":"A duration with years or months has no fixed length.","parameter":"filter[reading_time][le]"}
$ curl -g -H 'Accept-Language: es' 'localhost:8080/books?filter[colour]=red'
{…,"title":"Petición incorrecta","status":400,"code":"unsupported_parameter",
"detail":"No hay filtro por colour. Filtros: id, price, category, year, rating, published, reading_time, signed.","parameter":"filter[colour]"}
$ curl -i -X POST localhost:8080/books -H 'Content-Type: application/json' \
-H 'Idempotency-Key: "k-1"' -d '{"title":"Faros del norte","price":"12.00"}'
HTTP/1.1 201 Created
cache-group-invalidation: "/books", "/books/51"
etag: "6f0cf8ff79d65136cdaef2bbb9186452"
location: /books/51
{"id":"51","title":"Faros del norte","price":"12.00","category":"novela-negra","signed":false,
"_etag":"\"6f0cf8ff79d65136cdaef2bbb9186452\""}
$ # the same request again
HTTP/1.1 201 Created
idempotent-replayed: true
location: /books/51
$ curl -X POST localhost:8080/books -H 'Content-Type: application/json' -d '{"title":"No price","price":12}'
HTTP/1.1 422 Unprocessable Entity
{…,"code":"invalid","detail":"Invalid data.",
"errors":[{"pointer":"/price","code":"type","detail":"price must be a decimal in a string, such as \"18.50\"."}]}
$ curl -X PATCH localhost:8080/books/7 -H 'Content-Type: application/merge-patch+json' \
-H 'If-Match: "old"' -d '{"price":"17.00"}'
HTTP/1.1 412 Precondition Failed
{…,"code":"precondition_failed","detail":"Someone changed it: read it again before writing."}
$ curl -X PUT localhost:8080/books/7
HTTP/1.1 405 Method Not Allowed
allow: GET, PATCH, DELETE, HEAD
A resource that is one thing and not a collection, such as the shop itself (5.9). Declare it in singletons with its fields and a data that has get(ctx) and, for PATCH, update(merged, ctx); memorySingleton(object) does both in memory. Its relationships carry href:
singletons: {
shop: {
fields: { name: { type: 'string', required: true }, city: 'string', featured: { type: 'relation', to: 'categories' } },
data: memorySingleton({ name: 'El Marcapáginas', city: 'Bilbao', featured: { id: '2' } }),
},
},
$ curl localhost:8080/shop
{"name":"El Marcapáginas","city":"Bilbao","opening_hours":"L-S 10:00-20:00",
"featured":{"id":"2","href":"/categories/2"},"_etag":"\"b778fca8d85968051c74672bf461ec96\""}
GET and HEAD take fields and give an ETag, _etag and 304; PATCH works like an item’s (validation, If-Match, 428 with requireIfMatch); POST and DELETE give 405. A singleton has no id, language maps or actions, and its path cannot be one a collection or its items could have.
list and get are required; create, update and delete are optional, and each one you leave out takes its HTTP method away from the collection, from methods and item_methods in discovery and from the Allow of a 405. For your own domain errors, throw a RestepError:
import { RestepError, matches, sorter } from 'restep-server';
const books = {
async list({ filter, sort, limit, cursor, count }, ctx) {
// filter: [{ field, op, value, type }], already typed; sort: [{ field, desc, type }], ends in id.
// cursor: what you returned in next last time, or null. Return { items, next, total }.
},
async get(id, ctx) { /* the item, or null for a 404 */ },
async create(data, ctx) {
if (await isbnTaken(data.isbn)) throw new RestepError(409, 'conflict', 'That ISBN already exists.', { reason: 'duplicate' });
// ... store it and return it, with its id
},
};
matches, sorter, compareValues and valueAt are the comparison rules of 6.1 (exact decimals, dates and instants, durations, text by code points), for adapters that filter in memory. Any exception other than a RestepError becomes a 500 internal and goes to onError.
createServer(toNodeListener(api)).listen(8080); // Node http
app.use(toExpress(api)); // Express (with base: '/api' for app.use('/api', …))
app.all('*', toHono(api)); // Hono
export default { fetch: api.handle }; // Cloudflare Workers, Deno, Bun
With Express, mount it before express.json(): that parser answers malformed JSON itself, without problem+json. If a body parser has already read the body, toExpress serialises it again.
createRestep(options)Returns { handle, discovery, profiles, extensions }: handle(request) answers a Request with a Response; discovery(lang) gives the discovery document as an object; profiles and extensions are what it announces. A wrong configuration throws at start-up, with a message (in Spanish) that names the collection and the field.
| Option | Default | What it does |
|---|---|---|
collections | required | { name: collection }; see the next table |
singletons | none | { name: { path, description, fields, validate, requireIfMatch, data } } (5.9) |
base | '' | Path of the API root, such as /api |
version | '1' | The version of the discovery document |
languages | ['en', 'es'] | Languages of the library’s texts, only en and es; the first is the default |
languageTags | any | Tags the language maps accept; another gives 422 with code unknown |
secret | random | Key that signs the cursors (string or bytes). Set it when several instances serve the API |
idempotencyStore | in memory | Store for Idempotency-Key: reserve(key, print, ttlMs, ctx), atomic across processes, plus complete(key, response, ctx) and release(key, ctx). A durable store apart from the data is not enough for 7.1: see createTransaction |
createTransaction | none | (work, ctx) => …: wraps each write (POST, PATCH, DELETE) in one transaction of your database, so the effect and the stored response commit together, and If-Match is checked with the write. The connection reaches the adapter as ctx.transaction |
idempotencyTtl | 86400 | Seconds a key lasts; at least 86400 |
idempotencyAnonymous | true | false refuses an Idempotency-Key without credentials, with 400, and declares "anonymous": false (7.1). Going from true to false is a breaking change |
browserCredentials | 'auto' (false with oauth) | Whether the browser adds a request’s credentials by itself (5.8): then a POST, PATCH or DELETE from an origin that is neither the API’s nor in cors.origins gets 403 with no effect. 'auto': when it carries Cookie or Authorization: Basic/Digest; true, false, or (request) => boolean |
maxBodyBytes | 1 MiB | A larger body gives 413 |
docs | none | Documentation URL, or a list of { href, hreflang, title }: sent as Link: rel="service-doc" with discovery (4.2) |
status | none | { path: '/health', check: async () => true }: the service status of 4.4, 200 pass or 503 fail |
oauth | none | { authorizationServers, scopesSupported, verifyToken(token, request) }: announces oauth, serves the RFC 9728 metadata and the challenges of 11.5. verifyToken returns the principal or null |
authenticate | none | Without oauth: authenticate(request) returns a principal, null, or throws a RestepError 401 or 403 |
publicOrigin | the request’s | Public origin behind a proxy, for the oauth metadata and challenges and for the Origin check |
cors | none | true (any origin) or { origins: [...] }: answers the preflight and exposes ETag, Location, Link, Allow and the other headers a browser client needs. With a list of origins, every response carries Vary: Origin |
onError | console.error | Receives the exceptions that end in a 500 |
| Member | Default | What it does |
|---|---|---|
data | required | The adapter: list and get, and optionally create, update, delete |
fields | {} | { name: type } or { name: { type, required, description, values, to, title, default, labels, examples } }. id is added on its own. title, default (binding on create), labels for an enum and examples go into the create schema, to build a form (4.3). Names follow the grammar of 3, or it does not start |
filter | {} | { field: ['eq', 'in', …] } or { field: { ops, description } }. A field can be name, map.tag or relation.id; a boolean only takes eq, ne and null |
namedFilters | {} | { name: { description, type, apply } }: filters with a name (6.1), a switch without type or one that takes a value. They reach the adapter as { named, value }; memoryAdapter uses apply(row, value) |
collations | none | { field: 'codepoint' | 'server' }, only string fields (or field.tag) in filter or sort, never id. With 'server' your adapter compares (6.1) |
sort | [] | Sortable fields |
defaultSort | ['id'] | Order without sort, with - for descending. Ids compare as text, so "12" goes before "7" |
maxLimit, defaultLimit | 50, 20 | Page size: the most a limit may ask for, and the size without one |
count | none | 'exact' or 'estimated': allows count=true |
path | /name | A fixed path, without templates |
description | none | A string, or t('In English', 'En español') |
idFrom, idPattern | 'server' | Who picks the id (5.1): 'server' (an id in a POST gives 422 with read_only), 'client' (required) or 'either'. A taken one gives 409 with taken, and the adapter needs taken. idPattern restricts the client’s id |
newItem | none | (ctx) => body: adds the action GET /collection:new (11.1), the defaults plus what it returns, to start a form; it creates nothing |
validate | none | async (row, ctx) => errors: your own rules, a list of { pointer, code, detail } that ends in 422 invalid |
requireIfMatch | false | PATCH and DELETE without If-Match give 428 |
requireIdempotencyKey | false | A POST without Idempotency-Key gives 400 idempotency_key_required |
Field types are those of discovery (string, integer, number, decimal, boolean, date, datetime, duration, enum with values) plus map, a language map, and relation, to one item of the collection in to. From them it writes the item, create and update JSON Schemas of discovery.
| Method | Receives | Returns |
|---|---|---|
list(query, ctx) | { filter, sort, limit, cursor, count, fields } | { items, next, total } |
get(id, ctx) | The id in the URL, compared code point by code point (07 is not 7); before a PATCH or DELETE, with ctx.forUpdate: true, so lock it if there is a transaction | The item, or null for a 404, also when this principal cannot see it |
create(data, ctx) | The body, validated, without _ members; with id only if the client picked it | The stored item, with its id |
update(id, data, ctx) | The whole item, merged and validated; ctx.patch is the patch and ctx.current what was there. Not called if the PATCH changes no data | The stored item |
delete(id, ctx) | The id | Nothing |
taken(id, ctx) | An id the client picked; required with idFrom: 'client' or 'either' | true if the collection has or had that id, whether or not this principal sees it |
ctx carries request, principal, lang and collection. Filters and sort keys come with their collation. A field this principal cannot read in an item is absent for list, and total counts only what it sees: the library does not know who can read what.
| Export | What it is |
|---|---|
memoryAdapter(rows, { generateId }) | An in-memory adapter with all five methods, for tests and examples. New ids follow the largest numeric one, unless you pass generateId. Its rows is the Map behind it |
memorySingleton(object) | The same for a singleton: get and update in memory |
takenError() | The 409 conflict with taken, to throw from create when your primary key rejects a duplicate id |
memoryIdempotencyStore() | The default idempotencyStore, in memory |
RestepError(status, code, detail, extra) | Throw it to answer with a problem+json. extra adds members (reason, errors…) and headers |
t(en, es) | A text in both languages, for descriptions and details |
toNodeListener(api, { origin }) | Listener for node:http; origin sets the public origin behind a proxy |
toExpress(api, { origin }) | Express middleware; it uses req.originalUrl |
toHono(api) | Hono handler |
matches, sorter, compareValues, valueAt | The comparison rules of 6.1, for your own adapter |
mergePatch, canonical, pickLanguage | RFC 7396 Merge Patch, canonical JSON (the one behind ETags and idempotency) and the RFC 4647 lookup on Accept-Language |
DECIMAL, LANGUAGE_TAG, NAME | The regular expressions for a decimal string, a lowercase language tag and a name |
restep-server/pg is a transactional adapter for PostgreSQL 11 or later, with no dependencies: you give it a pool compatible with pg. The key, the created item and the stored response commit in one transaction, so a crash before the COMMIT undoes all three and one after it keeps all three for the retry. PATCH and DELETE read the item with FOR UPDATE, so If-Match holds across processes.
import pg from 'pg';
import { createRestep } from 'restep-server';
import { migrate, pgTransaction, pgIdempotencyStore, pgDocumentAdapter } from 'restep-server/pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
await migrate(pool); // once, when deploying
const api = createRestep({
collections: { books: { fields, data: pgDocumentAdapter({ pool, collection: 'books' }) } },
createTransaction: pgTransaction(pool),
idempotencyStore: pgIdempotencyStore(),
secret: process.env.RESTEP_SECRET, // the same on every instance
});
| Export | What it does |
|---|---|
schema(opts), migrate(pool, opts) | The SQL of the tables, and running it. opts: idempotencyTable, itemsTable |
pgTransaction(pool) | The createTransaction: BEGIN, the work on one connection, COMMIT, or ROLLBACK if it fails |
pgIdempotencyStore({ table }) | The key store. It needs ctx.transaction. Another request with the same key, from any process, gets 409 request_in_progress or 422 idempotency_mismatch without waiting |
pgDocumentAdapter({ pool, collection, table }) | A data adapter that keeps each item as jsonb, with ids from a sequence that are never reused. It has no taken, so no idFrom: 'client' or 'either'. It filters and sorts in the process: fine for tests and small collections; for large ones, write your adapter in SQL with the same contract |
inFlightReservations(pool), terminateReservation(pool, pid) | The transactions holding a key right now, and ending a stuck one: PostgreSQL rolls it all back, which proves there was no effect |
purgeExpired(pool, { table }) | Deletes stored responses past their time |
Effects outside PostgreSQL (payments, email, another database) are not in the transaction. It has been tested with PostgreSQL 14, READ COMMITTED and pg 8, killing processes before and after the COMMIT and stopping the database.
relations: it does not announce the profile, nor do include or subcollections (path with a template and parent). To-one relations are declared, validated and filtered by relation.id.sync: no collection declares it, and :changes gives 404. Of actions, only new on collections with newItem. inherit, batch, filter-expr and query-method, none: their parameters and paths fail loudly, with unsupported_parameter or 404.deprecations, announced, kind, Deprecation or Sunset (5.5), and no major versions such as /v2/.id is. A relationship sent back with its current value is ignored without checking it.403 for a field the principal may not change, the 409 for one the item’s state does not let change, unreadable fields in filters and total: your adapter and your validate do them (6.1).writes needs a transactional adapter such as the PostgreSQL one: the library’s own If-Match lock only covers one process, and the default key store lives in memory and forgets on restart.403 insufficient_scope is thrown by your verifyToken or your adapter.406 for Accept: it always answers JSON.A fake API from a discovery document, with plausible data, subcollections and actions. Filters, pages and fails like the real one, so the front end starts today.
Reads your OpenAPI 3 and lists, profile by profile, what keeps it from Restep. Then drafts the discovery document for you.