Declare your collections over your Active Record models. The gem does the protocol: discovery, filters, sort and cursors in SQL, problem+json errors in the order of the specification, ETags, conditional requests and idempotency. As a Rack app or inside your Rails controllers.
Ruby 3.4 or later · PostgreSQL · gem install restep
Declare each collection over a source: an Active Record model, or lambdas over whatever your domain computes, with ids that can be document keys. Discovery, reserved parameters, cursors, problem+json, Merge Patch, ETags, If-Match and Idempotency-Key come with the gem.
Nested collections
Paths such as /company_groups/{company_group}/policies/{policy}/drafts are templates: the gem finds each parent under the one before, answers 404 when one is missing, and carries the parents into links, cursors and cache groups.
Your discovery document as the contract
Generate discovery from the catalog, or hand the gem the document you wrote: it validates it at boot against the JSON Schema and the rules of draft 7, refuses to start on any disagreement with the code, and then answers every request by what it declares.
Measured against the checker
Two test servers on PostgreSQL built on this gem, plain Rack and idiomatic Rails, get 0 failures in restep-check--writes (277 passed). The gem’s own in-memory test API, with subcollections, relations and language maps, gets 0 failures and 0 warnings.
How it works
You give Restep.configure your collections, each a Restep::Collection with its fields and its source. For each request:
Restep::Envelope, the outermost middleware, answers unknown methods with 501, adds the profile link, and applies the CORS policy you chose: any origin, none, or a list, with the Origin check of 5.8 for APIs that take cookies.
Restep::Resolver matches the path against every path of the catalog, templates included, finds each parent item under the one before and then the item or the action (404), and which methods it allows (405 with Allow).
Restep::Context reads the raw query string and body, never Rails params: reserved parameters (400 with the parameter that failed), conditional headers, Content-Type (415), size (413, with the limit you set) and Accept (406).
Restep::Operations runs the operation through the source: lists get the parsed filters, sort and cursor position (SQL for Active Record, in memory for computed sources); writes validate the body against the fields (422 with one entry per field), check If-Match with the item locked (412) and turn conflicts into 409.
Each operation returns [status, headers, body] with ETag, Cache-Control and Cache-Groups set; RackApp or render_restep writes it as it is.
The cursor carries the source’s position (a keyset or an offset), encrypted and authenticated with AES-256-GCM, and bound to the collection with its parents, the filters, the sort and the principal. Its secret is one you give, shared by every replica; the gem never makes one up. The encryption is deterministic, so the same page always has the same body and the same ETag, and If-None-Match gives 304 on lists too.
Install
gem install restep
or, in your Gemfile:
gem "restep"
gem "json_schemer"# only to serve a hand-written discovery document
Ruby 3.4 or later and Rack 3. Active Record 8 is optional, for Restep::Sources::ActiveRecord, whose SQL is for PostgreSQL (see Limits).
Restep::Sources::Computed takes lambdas; the gem filters, sorts and pages the records in memory with the rules of 6. Each write lambda you leave out removes its method (405):
For anything else, subclass Restep::Source and implement list, find and the writes you offer.
With Rack
# config.rurequire_relative"app"# the declarations above
use Restep::Envelope # or cors: false, or cors: ["https://editor.example"]
run Restep::RackApp.new(logger: Logger.new($stderr)) # runs Restep.check! first
With Rails
# config/application.rbrequire"restep/rails"# concern, restep_action routes, railtie
config.middleware.delete Rack::ETag # Restep sets its own validators
config.middleware.delete Rack::ConditionalGet
config.middleware.insert_before 0, Restep::Envelope, cors: false, credentials: true# same origin, session cookie
config.exceptions_app = Restep::Rails::Controller.exceptions_app
# app/controllers/drafts_controller.rb: nested routes or notclass DraftsController < ApplicationController
include Restep::Rails::Controller
before_action { @restep = restep_context_for(restep_target) } # 404 with its parents, 405, then 400-406def index = render_restep(Restep::Operations.list(@restep))
def show = render_restep(Restep::Operations.show(@restep))
def create = render_restep(Restep::Operations.create(@restep))
def update = render_restep(Restep::Operations.update(@restep))
def destroy = render_restep(Restep::Operations.destroy(@restep))
end
The railtie derives the cursor secret from secret_key_base unless you set one, and runs Restep.check! after boot. restep_action :drafts, :publish in config/routes.rb routes an action such as POST …/drafts/7:publish, which the Rails router cannot express on its own.
A hand-written discovery document
Restep.configure do |c|
c.discovery = "config/discovery.json"# the contract: path, filters, sort, max_limit, actions… come from it
c.collections = { "drafts" => Restep::Collection.new(name: "drafts", source: DRAFTS_SOURCE, fields: DRAFT_FIELDS) }
end
At boot the document is validated against its JSON Schema and the rules of draft 7 the schema cannot express, and bound to the catalog: a collection, filter, sort key or action in one and not the other, a value the code says differently, or something the gem does not implement stops the application with every problem listed.
Examples
These answers come from the gem’s in-memory test API (test/workspace.rb): shelves with their notes at /shelves/{shelf}/notes, served by Restep::Sources::Computed on Puma. Use curl -g, or curl takes the square brackets for a pattern.
The reads are private because this API has a principal (config.principal), which the cursor is bound to as well.
Parents that do not exist
$ curl -g localhost:9393/shelves/attic/notes
{…,"status":404,"code":"not_found","detail":"There is no shelves item with id \"attic\"."}
$ curl -g localhost:9393/shelves/shelf-2/notes/note-4# note-4 is on shelf-1
{…,"status":404,"code":"not_found","detail":"There is no notes item with id \"note-4\"."}
$ curl -gi -X DELETE localhost:9393/people/ada# a computed source without delete
HTTP/1.1 405 Method Not Allowed
allow: GET, HEAD
Include and dotted fields
$ curl -g 'localhost:9393/shelves/shelf-1/notes/note-4?include=author&fields=title,author.name'
{"id":"note-4","title":"Buy flour",
"author":{"id":"ada","href":"/people/ada","name":"Ada Lovelace","_etag":"\"eaf062d9de9d396b348030ac58648cf1\""},
"_actions":{…},"_etag":"\"7014be73539d442281afb0645a036f7d\""}
$ curl -g 'localhost:9393/shelves/shelf-1/notes/note-4?fields=title,author.name'
{…,"code":"invalid_parameter","detail":"author.name needs include=author: a dotted path in fields goes into an included relationship.","parameter":"fields"}
Writes, with a language map
$ curl -X POST localhost:9393/shelves/shelf-2/notes -H 'Content-Type: application/json' \
-d '{"title":"Sweep","summary":{"en":"Sweep","ES":"Barrer"}}'
{…,"status":422,"code":"invalid","errors":[{"pointer":"/summary/ES","code":"format",
"detail":"ES is not a well-formed lowercase language tag (BCP 47), such as es-es."}]}
$ curl -i -X POST localhost:9393/shelves/shelf-2/notes -H 'Content-Type: application/json' \
-d '{"title":"Sweep","author":{"id":"grace"},"summary":{"en":"Sweep","es-es":"Barrer"}}'
HTTP/1.1 201 Created
location: /shelves/shelf-2/notes/note-a
cache-group-invalidation: "/shelves/shelf-2/notes", "/shelves/shelf-2/notes/note-a"
{"id":"note-a","title":"Sweep",…,"author":{"id":"grace","href":"/people/grace"},"summary":{"en":"Sweep","es-es":"Barrer"},…}
The gem’s tests run this themselves inside the site’s repository (test/checker_test.rb, Puma in the same process).
API
Restep.configure
Option
Default
What it is
collections, singletons
{}
{ "name" => Restep::Collection }: the collections and singletons of the API (5.9)
cursor_secret
none: required
The secret the cursor keys derive from, shared by every replica, of at least 16 bytes. RESTEP_CURSOR_SECRET works too; the Rails railtie derives one from secret_key_base. Never generated (6.4)
principal
none: anonymous
->(request) { "user-7" or nil }: who the request acts for (2). Idempotency keys and cursors belong to it, and reads become private
idempotency_model, idempotency_store
none
Where Idempotency-Key records live (7.1): an Active Record model on PostgreSQL (columns principal, http_method, path, key, request_hash, completed, status, headers, body, expires_at), or any store, such as Restep::Idempotency::MemoryStore for one process
idempotency_anonymous
true
false refuses Idempotency-Key on requests without a principal, and says so in discovery
discovery
none: generated
A hand-written discovery document, as a path or a Hash, validated and enforced (4.2)
max_body_bytes
65536
The largest request body; above it, 413
reasons
{}
Catalogue of domain reasons for 409 and 422, published in discovery (5.4)
docs_path, docs_language
none, "es"
Documentation for people, served at /docs and linked from discovery with rel="service-doc"
root_path
""
Path of the API root without the final slash, such as "/v1". Links include it; discovery paths do not
Restep::Collection.new
Argument
What it is
name, path, description
Name in discovery, path relative to the API root (a URI template for a subcollection), description
parent
For a subcollection, or a singleton under an item: the collection it hangs from (4.2)
model or source
An Active Record model, or its name; or any Restep::Source: Restep::Sources::ActiveRecord.new(model, parent_column:), Restep::Sources::Computed.new(all:, find:, get:, create:, update:, delete:, …) or your own subclass
fields
Restep::Fields.f(name:, type:, …) with column, values, nullable, required, default, read_only, max_length, pattern, range, scale, relation, include, languages, schema, validate and description. Types: id, string, enum, integer, decimal, boolean, date, datetime, relation (to one item; include: true lets it be expanded, 9), language_map (3), and object and array for any JSON document the item carries: checked as I-JSON, described by schema: in the schemas of discovery (4.3), merged member by member in a PATCH (an array is replaced), and filtered only by a dotted path to a member with its own sql: or value:. validate: ->(value, pointer) { errors or nil } adds your own 422 entries to any field
filters
{ "field" => { "type", "ops" } }, plus sql: (Active Record; without it, the field’s column) or value: (computed); "required" => true for a filter every list request must carry. A translation is filtered as "field.tag"
named_filters
{ "name" => { "description", sql: ->(value) { ["SQL ?", value] } } }, or match: ->(record, value) { … } on a computed source (6.1); a switch may be "default" => true
sort
{ "field" => { sql: "column", type: "string" } } or {} for the field’s own; the order always ends in id
max_limit, default_limit, count
Page size (6.4) and "exact", "estimated" or nil (6.5)
methods, item_methods
What the collection and its items support; by default, what the source implements (4.3)
relations, include_depth
Relationships declared only in discovery, such as the one that leads to a subcollection, and how deep include goes
conflicts
{ unique: ->(rec) { Restep::Problem }, foreign_key: ->(rec) { … } }: the 409 for a database constraint
actions
Restep::Fields.action(name, on: "item" | "collection", method:, safe:, idempotent:, input:, output:, effects:, available:, unavailable:, run:) (11.1). A collection action’s run receives the source’s scope for the parents. An unsafe action answers what 11.1 allows: on an item, the item (200), Restep::Created.new(location) (201 with Location) or Restep::NO_CONTENT (204); on a collection, Restep::Created or [204, nil], never 200. A safe action returns [200, result] or [204, nil], and may use POST to take an input: the way to compute a result, such as a diff, from data in the body
singleton, method_effects
true for a singleton, and the effects of its PATCH
max_body_bytes
This collection’s body limit
Restep::Envelope
Option
What it does
cors: "*"
The default: Access-Control-Allow-Origin: * on every response and the preflight answered
cors: false
No CORS: a same-origin API. OPTIONS goes on to the application
cors: ["https://…"]
Only those origins, named back, with Vary: Origin on every response
credentials: true
The API takes credentials a browser sends on its own (cookies): an unsafe request from an origin that is neither the API’s nor in cors gets 403 (5.8), and allowed origins get Access-Control-Allow-Credentials
exempt: ->(env) { … }
With credentials: true, the requests your application authenticates only with a token a browser never attaches on its own, which 5.8 does not cover: they skip the Origin check. Restep::Envelope.method(:token_authorization?) takes any Authorization scheme but Basic, Digest, Negotiate and NTLM
path: "/v1"
Only requests under that path (or list of paths) get the envelope; the rest of the application, such as its HTML pages, is left untouched, Rails’ params included
Pieces
Constant
What it does
Restep::RackApp
The whole API as one Rack app; it runs Restep.check! when created. logger: receives the exceptions that end in a 500
Restep.check!
Validates the configuration and raises Restep::ConfigurationError with every problem
Restep::Source
The seam with your domain: list(query, parents), find(id, parents), find_singleton, create, update, delete, transaction, lock
Restep::Rails::Controller
Concern: restep_target, restep_context, render_restep, rescue_from to problem+json, exceptions_app
resolve(path) (a Target with kind, collection, record, action and parents), method_not_allowed: steps 1 and 2 of 5.4
Restep::Rules
The rules of draft 7 for a discovery document, and its JSON Schema
Restep::Problem
A Restep error: raise Restep::Problem.new(409, "conflict", reason: "duplicate", detail: "…"), with the closed table of codes of 5.4
Restep::Body
parse(raw, decimal_class: BigDecimal) parses a raw body as an I-JSON message (400 on bad JSON or a repeated member) without a Restep::Request; media_type! gives the 415; read does both for any object with raw_body and content_type; object! gives the 422 of a body that is not an object. decimal_class: nil gives Float
Restep::Conditional
parse and evaluate for If-Match and If-None-Match (7.2): an empty header is an empty list, which no ETag matches
Restep::QueryString
The raw query string as pairs, repeated names and brackets kept; a % that starts no escape gives 400
Restep::MergePatch
apply(target, patch): JSON Merge Patch (RFC 7396)
Restep::Idempotency::ActiveRecordStore
new(model, unique_by:, purge_every: 3600): finds the unique index by its columns, whatever its name, and deletes every expired key once per purge_every seconds; purge for a job
The gem owns the top-level constant Restep and everything under it. An application with its own Restep::* constants clashes with it (with Zeitwerk, its files are ignored as shadowed): rename that namespace, for example under your application’s own module.
Limits
PostgreSQL for Active Record. Filters and cursors write PostgreSQL casts (::bigint, ::numeric, ::date, ::timestamptz) and the idempotency table locks its record with FOR UPDATE NOWAIT. Text columns should use COLLATE "C", because discovery declares the codepoint collation.
Computed sources filter, sort and page in memory: right for what fits in memory under one parent.
Profiles core, query, writes, cache and relations, and the actions extension. No sync, batch, filter-expr, query-method, oauth or inherit; no localized fields, local date-times, durations, upload, upsert or reusable_ids; relations are to-one and to one collection; filters do not go through to-many relations; actions take no params.
The server assigns the ids (id_from is server).
Draft 7 of the specification only: discovery declares "restep": "1.0-draft.7".
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.