Restep2½

Tools · Build an API · v0.4.1

restep-mockAn API before the API

Give it a discovery document and it serves a fake API with plausible data. It filters, sorts, pages and fails like the real one, so the front end and the agents can start today.

Node 18 or later · npm install -g restep-mock

Why use it

The front end starts today

Write the discovery document, start the mock and build the client, the agent or the interface against it. The back end can arrive later and answer the same way.

Not a cardboard server

It filters with every operator, sorts, pages with signed cursors, validates writes, honours If-Match and Idempotency-Key, and serves subcollections and actions. restep-check --writes finds no failures in it.

Data that looks real, every time

Emails, names, prices as decimal strings, updated_at after created_at. Same seed and same discovery, same data. And a few gaps on purpose, so null has something to test.

Bad days on demand

--latency and --fail-rate give you slow answers and 503s with Retry-After, so your retries get tested before production tests them for you.

How it works

  1. It reads a discovery document (4.2) from a file or from the root of an API, following Link: rel="service-desc" when the root is not the document, and the schemas linked in schemas.
  2. It works out each collection’s fields and types: first from the item or create schema, then from the types in filter, and language_maps, relations and inherit. Without a schema, from the names: *_at is a datetime, price a decimal, is_* a boolean.
  3. It generates the data from the seed, one value per collection, item and field, so adding a field does not change the others. Relations point at items that exist, and never in a cycle.
  4. It serves the discovery document as it came, minus what it does not implement (it says so on stderr), and answers like a real draft 6 server of the core, query, writes, cache and relations profiles and the actions and inherit extensions, with subcollections. It takes any Restep 1 version that follows the grammar of 1.1, but always declares "restep": "1.0-draft.6", the text it implements (1.2), and warns you if the document said otherwise.

Writes live in memory and are gone when you stop it. Ids are "1", "2"…, under each parent item in a subcollection, and new items continue the count.

Run it

Node 18 or later, no dependencies. Run it with npx, or install it with npm install -g restep-mock (or npm install --save-dev restep-mock for a project’s front end).

npx restep-mock discovery.json                  # http://localhost:8090/
npx restep-mock https://api.example.com/ --port 9000

It exits with code 2 when it cannot start: a misspelled option, a missing file, JSON that is not a discovery document, a port in use. Its console messages are in Spanish for now; the API it serves speaks English or Spanish, after Accept-Language.

Examples

From a discovery document

A collection of books with two filters, no schema. The mock guesses that title is text from its name:

{
  "restep": "1.0-draft.6", "version": "1",
  "profiles": ["core", "query", "writes"],
  "idempotency": { "ttl": 86400 },
  "collections": {
    "books": {
      "path": "/books",
      "methods": ["GET", "POST"], "item_methods": ["GET", "PATCH", "DELETE"],
      "filter": {
        "price": { "type": "decimal", "ops": ["lt", "ge"] },
        "published_at": { "type": "datetime", "ops": ["ge"] }
      },
      "sort": ["id", "title", "price"],
      "max_limit": 20, "count": "exact"
    }
  }
}
$ npx restep-mock discovery.json
restep-mock 0.4.1 · Restep 1 (core, query, writes) en http://localhost:8090/
Colecciones: books (50) · semilla 1

$ curl -g 'localhost:8090/books?filter[price][lt]=20&sort=-price&limit=2&count=true&fields=title,price'
{"items":[{"id":"18","title":"El último ferry a Getxo","price":"17.88","_etag":"\"f0cc4b16a4a8d2d4\""},
          {"id":"33","title":"Lluvia sobre Mundaka","price":"15.91","_etag":"\"5f696cf5bf93f0d7\""}],
 "next":"/books?filter%5Bprice%5D%5Blt%5D=20&sort=-price&limit=2&count=true&fields=title%2Cprice&cursor=eyJvIjoyLCJxIjoi…",
 "total":8}

$ curl -g 'localhost:8090/books?filter[published_at][ge]=2025-01-01'
{…,"code":"invalid_parameter","detail":"2025-01-01 is not a valid RFC 3339 date-time with offset.","parameter":"filter[published_at][ge]"}

$ curl -i -X POST localhost:8090/books -H 'Content-Type: application/json' -d '{"title":"Faros del norte","price":"12.00"}'
HTTP/1.1 201 Created
Location: /books/51
ETag: "03433a1a32952ba9"
{"id":"51","price":"12.00","title":"Faros del norte","_etag":"\"03433a1a32952ba9\""}

$ curl -i -X POST localhost:8090/books -H 'Content-Type: text/plain' -d 'x'
HTTP/1.1 415 Unsupported Media Type
{…,"code":"unsupported_media_type","detail":"Send application/json, in UTF-8."}

Every item carries _etag, because the collection accepts PATCH and DELETE. Use curl -g, or curl takes the square brackets for a pattern. The generated data is in Spanish, like the reference implementation’s bookshop: titles full of Basque place names, Spanish personal names, @example.com emails.

A twin of an API that already exists

Give it the root of a running API and it copies its discovery document, not its data. Handy for testing against 200 items when the real one has 7. Here, the reference server, with its shop singleton and its reviews subcollection, three under each book:

$ npx restep-mock http://localhost:8080/ --port 8092 --count 200
restep-mock 0.4.1 · Restep 1 (core, query, writes, cache, relations) en http://localhost:8092/
Colecciones: books (200), products (200), categories (200), authors (200), reviews (600) · semilla 1

$ curl -g 'localhost:8092/products?limit=2&fields=name'
{"items":[{"id":"1","name":{"en":"Glass notebook","es":"Cuaderno de cristal","es-mx":"Cuaderno de cristal"},"_etag":"\"74b758368451e50e\""},
          {"id":"10","name":{"en":"Travel folder","en-gb":"Travel folder"},"_etag":"\"ba175f47b39f5530\""}],"next":"/products?limit=2&fields=name&cursor=…"}

$ curl localhost:8092/shop
{"name":"Espacio Ondarroa","email":"iker.vidal1@example.com","phone":"+34 636 305 154","max_reservations":675,"_etag":"\"112ed2b4a6d22dbc\""}

Language maps get the tags discovery uses in filter and sort, plus en and es, with translations missing here and there, as in life.

Outages and latency

$ npx restep-mock discovery.json --fail-rate 0.5 --latency 50-200 --retry-after 3
$ curl -i localhost:8090/books?limit=1
HTTP/1.1 503 Service Unavailable
Retry-After: 3
{"type":"https://w3id.org/restep/1/errors#unavailable","title":"Service unavailable","status":503,
 "code":"unavailable","detail":"Simulated outage: try again later."}

A 503 comes before anything else happens: a write that fails this way has no effect and does not spend its Idempotency-Key. The status resource never goes down, so a client can tell a passing failure from a dead API. Latency and failures follow the seed, in the order requests arrive.

Just the data

$ npx restep-mock discovery.json --dump --count 3
{
  "books": [
    { "id": "1", "price": "91.96", "published_at": "2020-01-02T14:15:00Z", "title": "Los faros de Deusto" },
    { "id": "2", "price": "35.21", "published_at": "2021-02-23T15:30:00Z", "title": "Mareas de Algorta" },
    { "id": "3", "price": null, "published_at": "2025-01-21T14:30:00Z", "title": "El último ferry a Bermeo" }
  ]
}

Fixtures for your tests, without starting a server. Around 10% of optional fields are null on purpose.

Check it

$ npx restep-check http://localhost:8092/ --writes
…
0 failed · 1 warning · 531 passed · 50 skipped

That is the twin of the reference server, with restep-check 0.9.1. The warning is discovery.service-doc: the mock does not send a rel="service-doc" link to your documentation. The skips are restep-check’s, not the mock’s: what needs credentials or CORS, and similar.

Subcollections

A collection with a parent and a template in its path (4.2) is served under each item of its parent, at any depth: /books/{book_id}/reviews, or /authors/{author_id}/books/{book_id}/reviews. First it checks what the specification asks: a declared parent, variables with distinct names, and a path that is its parent’s followed by /, its variable and something more with no variables. One that does not comply is left out with a warning, and so is whatever hangs from it.

$ curl 'localhost:8092/books/7/reviews?limit=2'
{"items":[{"id":"1","rating":3,"text":"Uno de los favoritos de la clientela habitual.","_etag":"\"b581e6e91f3fea13\""},
          {"id":"2","rating":4,"text":"Existencias limitadas: pregunta antes de venir.","_etag":"\"e0fd3d950820dfa2\""}],
 "next":"/books/7/reviews?limit=2&cursor=…"}

$ curl localhost:8092/books/999/reviews
{…,"code":"not_found","detail":"/books/999/reviews does not exist."}
  • Each parent item has its own items, three by default (or --count reviews=n per parent), with their own ids: /books/7/reviews/1 and /books/12/reviews/1 are different.
  • A path under a parent that does not exist gives 404. A POST creates under that parent, with the whole path in Location; id_from, taken, cursors and cache groups go per parent (5.1).
  • Deleting an item deletes its subcollections, with their descendants, and the links that pointed at them. Their ids are never given out again.
  • A link to an item of a subcollection carries its href (3), and writing one requires it: without it, or with one that is not the path of an item of that collection ending in its id, you get 422. In the generated data, a link to a subcollection that hangs from the item itself or from one of its parents stays under that parent: a book’s highlight is a review of that book.

Actions

The mock does not know what an action does (11.1), so a simulated action changes no data. It checks everything the specification defines and answers something conforming:

$ curl -X POST localhost:8092/products/3:restock -H 'Content-Type: application/json' -d '{"quantity":0}'
{…,"code":"invalid","errors":[{"pointer":"/quantity","code":"range",…}]}

$ curl -i -X POST localhost:8092/products/3:restock -H 'Content-Type: application/json' -d '{"quantity":4}'
HTTP/1.1 200 OK
ETag: "4f03b7b6140b7372"
{"id":"3",…,"stock":105,…,"_etag":"\"4f03b7b6140b7372\""}
  • Where. POST /collection/{id}:name or /collection:name (also with %3A), depending on its on. An action the collection does not declare, or asked for on the other kind of resource, gives 404, like an item that does not exist; another method, 405 with Allow; a reserved parameter, unsupported_parameter.
  • The body. Empty, with or without Content-Type, it is {}; otherwise it follows 3 (415, 400). It is validated against its input, embedded or linked, with 422 invalid and one entry per failure. Without an input it can read, it takes any object, and warns you.
  • Retries. An action with "idempotent": false follows 7.1 with Idempotency-Key, "anonymous" included; one with "idempotent": true never refuses the key: it ignores it and stores nothing. If-Match and If-None-Match are evaluated against the item, or against the collection for a collection action.
  • What it answers. The affected resource (200): the item, with its _etag and ETag, or the first page of the collection for a GET collection action. A collection action with POST answers 204, and an item action with Prefer: return=minimal, 204 with the ETag. Never 201 or 409.
  • What it does not serve. An action named changes, a GET one that is not safe or that has an input, or one with an on or a method draft 6 does not define.

Options

OptionWhat it does
<discovery.json | URL>The discovery document: a file, or the root of an API
--port nPort (8090; 0 picks a free one)
--host hostInterface it listens on (all)
--seed nSeed for the data, the cursor signature and the failures (1)
--count nItems per collection (50)
--count coll=nItems in one collection; in a subcollection, per parent item (3). Repeatable
--latency ms|a-bDelay for every answer: fixed (120) or random in a range (0-300)
--fail-rate 0..1Share of requests that get 503 unavailable in problem+json, with Retry-After
--retry-after sSeconds of Retry-After in those 503s (1)
--dumpWrites the generated data as JSON to stdout and exits, without a server
--quietNo warnings on stderr
-h, --helpThe help

With a file, linked schemas are looked up next to it: /schemas/x.json is schemas/x.json in the file’s folder. Schemas linked with an absolute path are served at that same path.

What it simulates

  • Discovery: the document it gets, untouched, except for what it does not implement (below) and the declared version, always "1.0-draft.6". Another major version, or a malformed restep, does not start.
  • core: items and next, items at path/id (each segment compared after decoding: /books/%37 is /books/7), HEAD wherever GET is declared, 405 with Allow from methods and item_methods, 404 not_found, the error order of 5.4, reserved parameters that fail with unsupported_parameter (also $anything, also on writes), problem+json in English or Spanish (5.6), and language maps. The media types of 3: 415 without Content-Type, with another type or with a charset other than UTF-8 (with Accept-Patch on a PATCH), and 400 to an empty body. Who picks the id (id_from, 5.1): "server" (a POST with an id gives 422 with read_only at /id), "client" or "either", with 409 conflict and taken for an id the collection has or has had. Read-only fields are ignored with their current value and give read_only with another; a relationship to an item that does not exist gives unknown. Singletons (5.9): GET, HEAD and, if declared, PATCH; POST and DELETE give 405. And the service status (4.4) if discovery declares one.
  • Deprecations (5.5): whatever uses something announced in deprecations (any kind, at the root, on a collection or on a singleton) carries Deprecation and a Link with rel="deprecation", and Sunset when a collection, a singleton or the version goes. After the sunset, it applies the retirement of filter, operator, sort, include, count, max_limit, method and item_method (it stops declaring them), and of whole collections and singletons (410 retired).
  • query: every operator and type of 6.1 (exact decimals, instants with offsets, durations by length, booleans, text by code points, field.tag, relation.id and relation.field), sorting with missing values last, collations ("server" compares ignoring case and accents, 6.1), fields, limit within max_limit, signed cursors bound to collection, filters and sort, and count; estimated rounds to tens and adds total_estimated. Without max_limit or count declared, limit or count give unsupported_parameter.
  • writes: POST, PATCH (Merge Patch, also as application/json) and DELETE, 422 invalid with one entry per problem, Idempotency-Key (the query counts towards the same request, and "anonymous": false refuses a key without credentials with 400), strong ETags, _etag on every response whose body is an item and on every listed item that accepts PATCH or DELETE, If-Match and If-None-Match (on a POST to a collection too), 404 to a write on a deleted item, and Prefer: return=minimal with the item’s ETag.
  • cache: Cache-Control on every response to GET or HEAD, errors included, ETag and 304, and Cache-Groups and Cache-Group-Invalidation (8), those two only if the discovery document announces cache.
  • inherit: inherited values (11.6) with _inherited, cycles refused and real sources. If a collection declares inherit, the discovery document it serves announces the extension, and warns you if the original did not, as in draft 5.
  • Subcollections and actions: see their sections, above.
  • relations (9): include up to include_depth on relations with "include": true; dotted fields, which require the include and a field that exists on the included item; to-many relations as unpaginated lists; relations to several collections with type, whose include fills in the item of that collection and goes no deeper; a related item that does not exist stays as its {id}. Links to items of a subcollection carry href, also when included. The to-many relation whose path is the template of a subcollection of its own collection leads to it: it is not embedded in the representation, include brings its items, and it is not written. A path through a to-many relation, or one ending in the id of an item of a subcollection, is not served in filter or sort (6.1). Deleting an item removes the links to it.

What it does not simulate

It removes these from the discovery document it serves, and says so on stderr, so it never announces what it does not do:

  • The sync profile and the batch, filter-expr, query-method and oauth extensions, and the sync, batch and events members.
  • Subcollections that do not comply with 4.2 and actions that do not comply with 11.1.
  • Singletons with a template or parent (5.9 reserves them), and relationship or language map fields on a singleton.
  • An id_from with a value draft 6 does not define.
  • Deprecation notices with a kind out of place, and expired ones of field, value, relation, action, version, extension and reason.

And also:

  • Schema validation covers types, required, enum, minimum, maximum, minLength, maxLength and pattern of top-level fields; not allOf, $ref, nested objects, or format beyond dates and durations.
  • Any well-formed tag goes in a language map: it never gives the unknown code of 3.
  • What actions do: they change no data, create nothing (201), give no 409 for the item’s state and are not listed in _actions, which is optional. Restep 1 has no output schema for an action, so it generates no answer other than the affected resource.
  • A relation to a collection that is not in discovery, or that it leaves out, stays null.
  • Texts in discovery stay in the language they came in; only errors follow Accept-Language.
  • Writes and idempotency keys live in memory, and the cursor is not bound to the principal.
  • No credentials: no response depends on them, there is no 401 or 403, and no Origin check (5.8).
  • On a POST, a read-only field other than id is only ignored when it is null: the mock does not work out “the value the item would get” (4.3).
  • No service-doc link (4.2): it does not know the documentation of the API it fakes.

All the tools