Restep2½

Tools · Check · draft 6

JSON SchemasValidate the shape

Two JSON Schemas for the two documents Restep defines: the discovery document at the API root and every error body. Drop them into your tests, your editor or any 2020-12 validator.

JSON Schema 2020-12 · any validator

Why use them

Mistakes caught while typing

Point your editor at the discovery schema and a filter type of money or an operator like is underlined before anyone runs anything.

One line in your tests

Validate your discovery document once and every error your API returns. A missing code fails the build, not a client six months later.

Standard JSON Schema

Draft 2020-12, no custom keywords. Ajv, Python’s jsonschema, check-jsonschema, your IDE: anything that speaks 2020-12.

Honest about their reach

They check the shape of a document. What depends on the HTTP response or on the rest of the API is restep-check’s job, and the list below says which is which.

The two schemas

SchemaFor
/1/schema/discovery.jsonThe discovery document at the API root (4.2)
/1/schema/problem.jsonEvery error body, application/problem+json (5.4)

Their $id is a permanent identifier under https://w3id.org/restep/1/schema/, which redirects to these files; download them from here. They change with the specification’s draft, so in a test suite keep a copy next to your tests rather than fetching them on every run:

mkdir -p test/schema && cd test/schema
curl -O https://restep.wubytes.com/1/schema/discovery.json
curl -O https://restep.wubytes.com/1/schema/problem.json

What they check, and what they do not

discovery.json

  • restep is present and of the form 1.x, without leading zeros, with an optional -draft.N or -rc.N: "1.0", "1.0-draft.6" (1.1); version is an integer string such as "2".
  • Only the members Restep defines, plus x- members for what a server adds outside Restep, at the root and inside each object it defines (4.2).
  • Profile dependencies: sync, filter-expr and query-method need query; the batch extension needs a batch object with its path; a collection declares inherit only if extensions lists it (11.6).
  • Names follow the grammar of 3: a letter, then up to 63 letters, digits, _ or -, so none starts with _. That goes for collections, singletons, relations, actions, named filters and inherited fields; filter and sort keys are such names joined by dots.
  • Paths start with /. A collection’s template uses simple variables with distinct names, and a collection with a template declares parent (4.2). status and linked schemas are an absolute path or an https or http URI.
  • Singletons have a path without a template, and methods from GET and PATCH that include GET (5.9).
  • Filters: a type from the vocabulary (string, integer, number, decimal, boolean, date, datetime, duration, enum), ops from the list (eq, ne, lt, le, gt, ge, in, null), values on every enum, only eq, ne and null on a boolean, and no order operators on id.
  • id_from is server, client or either (5.1); each entry of collations is codepoint or server, and never for id (6.1).
  • A collection with sync declares filter on id with in (10).
  • methods and item_methods only hold GET, POST, PATCH and DELETE; descriptions are non-empty strings.
  • Actions have on, safe and idempotent, a name other than changes, and use GET only when safe and without input.
  • max_limit and include_depth are at least 1, count is exact or estimated, idempotency.ttl is at least 86400 and idempotency.anonymous a boolean.
  • Deprecations carry an RFC 3339 announced, a kind that fits where they are (the root, a collection or a singleton), a name unless the kind is version, count or max_limit, the op or value their kind needs, and an optional sunset (5.5). reasons are snake_case, each with its code.
  • The shapes of relations, language_maps and inherit.

It does not know whether a relation’s to names a real collection, whether language_maps or inherit point at the right fields, whether a collation is on a declared string field, whether a named filter shares its name with a filter, whether a subcollection’s path starts with its parent’s, or whether a filter or sort key goes through a to-many relationship. Those rules of the text do not fit in a schema, but they need no request either: restep-check --schema discovery runs them too, and reports them apart (below). What only a running server shows, such as whether a filtered or sorted field exists in the items or whether methods agree with the Allow it sends, restep-check checks against the API. A member that is neither Restep’s nor x- fails: clients ignore members they do not know, but a server only adds its own with x-.

problem.json

  • type, title, status and code are present; status is between 400 and 599.
  • code is snake_case; reason follows the grammar of names (3); type and instance are URI references.
  • Each entry of errors has a code and at least one of pointer (a JSON Pointer), parameter or header.

It does not know the response around the body: whether status equals the HTTP status, whether code is the one the table of 5.4 gives for that status, whether invalid_parameter names its parameter, whether a reason is declared in discovery, or whether the Content-Type is application/problem+json. restep-check checks all of those on every response it sees.

Examples

With restep-check

restep-check carries both schemas. It takes files, URLs or - for standard input.

npx restep-check --schema discovery https://api.example.com/
curl -s https://api.example.com/nope | npx restep-check --schema problem -

A discovery document with three mistakes in it:

{
  "restep": "1.0",
  "profiles": ["core", "sync"],
  "collections": {
    "books": {
      "path": "/books",
      "filter": {
        "price": { "type": "money", "ops": ["eq", "like"] },
        "_secret": { "type": "string", "ops": ["eq"] }
      }
    }
  }
}
$ npx restep-check --schema discovery bad.json
FAIL  bad.json
  Schema (discovery.json): 8 errors
      /profiles/0: must be equal to constant
      /profiles/1: must be equal to constant
      /profiles: must contain at least 1 valid item(s)
      /: must match "then" schema
      /collections/books/filter: must match pattern "^[A-Za-z][A-Za-z0-9_-]{0,63}(\.[A-Za-z][A-Za-z0-9_-]{0,63})*$"
      /collections/books/filter: property name must be valid
      /collections/books/filter/price/type: must be equal to one of the allowed values
      /collections/books/filter/price/ops/1: must be equal to one of the allowed values
  Rules of the text that the schema cannot express: 5 failed · 0 warnings · 2 passed · 0 skipped
    FAIL discovery.dependencies  No profile or extension without the ones it requires
         sync without query
         MUST · §1.2 https://restep.wubytes.com/1/#dependencies
    FAIL discovery.names  Every name discovery declares (…) follows the grammar of names
         names outside the grammar: books filter "_secret"
         MUST · §3 https://restep.wubytes.com/1/#data
    FAIL discovery.types  Filter types come from the vocabulary; enum carries values
         books.price: type "money"
         MUST · §4.2 https://restep.wubytes.com/1/#discovery
    FAIL discovery.ops  Operators come from the list; (…)
         books.price: operator like
         MUST · §6.1 https://restep.wubytes.com/1/#filters
    FAIL discovery.no-underscore-fields  No declared field starts with _
         fields starting with _: books._secret
         MUST · §3 https://restep.wubytes.com/1/#data

The first four schema lines are one mistake: sync without query, which the rules say in one line (discovery.dependencies). A document the schema accepts but that breaks three rules of the text: a named filter called like a key of filter, a subcollection whose path does not start with its parent’s, and a filter through a to-many relationship:

{
  "restep": "1.0-draft.6",
  "profiles": ["core", "query", "relations"],
  "collections": {
    "books": {
      "path": "/books",
      "filter": {
        "title": { "type": "string", "ops": ["eq"] },
        "reviews.rating": { "type": "integer", "ops": ["ge"] }
      },
      "named_filters": { "title": { "description": "Title contains the text." } },
      "relations": { "reviews": { "to": "reviews", "many": true } }
    },
    "reviews": { "path": "/reviews/{book_id}", "parent": "books" }
  }
}
$ npx restep-check --schema discovery rules.json
FAIL  rules.json
  Schema (discovery.json): valid
  Rules of the text that the schema cannot express: 3 failed · 0 warnings · 8 passed · 0 skipped
    FAIL discovery.subcollections  A collection whose path is a template declares parent, (…)
         reviews: /reviews/{book_id} does not start with its parent’s path /books, / and its last variable
         MUST · §4.2 https://restep.wubytes.com/1/#discovery
    FAIL discovery.named-filters  named_filters is an object of objects with a description (…)
         books.title is both a filter and a named filter
         MUST · §6.1 https://restep.wubytes.com/1/#filters
    FAIL query.filter.lists [books]  No field holding a list, no path through a to-many relationship (…)
         reviews.rating goes through the to-many relationship reviews
         MUST · §6.1 https://restep.wubytes.com/1/#filters

And two error bodies that look fine at a glance:

$ echo '{"type":"about:blank","title":"Not Found","status":404}' | npx restep-check --schema problem -
FAIL  -
  Schema (problem.json): 1 error
      /: must have required property 'code'
$ echo '{"type":"about:blank","title":"Not Found","status":200,"code":"NotFound"}' | npx restep-check --schema problem -
FAIL  -
  Schema (problem.json): 2 errors
      /status: must be >= 400
      /code: must match pattern "^[a-z][a-z0-9_]*$"

Against the reference server, both pass:

$ npx restep-check --schema discovery http://localhost:8080/
PASS  http://localhost:8080/
  Schema (discovery.json): valid
  Rules of the text that the schema cannot express: 0 failed · 0 warnings · 26 passed · 0 skipped
$ curl -s http://localhost:8080/books/999 | npx restep-check --schema problem -
PASS  -
  Schema (problem.json): valid

In Node tests

With node:test and Ajv (npm install -D ajv ajv-formats). strict: false silences Ajv’s strict-mode warnings about keywords such as contains used without a type beside them; restep-check does the same.

// test/restep.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import Ajv from 'ajv/dist/2020.js';
import addFormats from 'ajv-formats';

const API = process.env.API ?? 'http://localhost:8080/';
const load = async (f) => JSON.parse(await readFile(new URL(`./schema/${f}`, import.meta.url), 'utf8'));
const ajv = addFormats(new Ajv({ allErrors: true, strict: false }));
const discovery = ajv.compile(await load('discovery.json'));
const problem = ajv.compile(await load('problem.json'));

test('the discovery document has the right shape', async () => {
  const doc = await (await fetch(API)).json();
  assert.ok(discovery(doc), ajv.errorsText(discovery.errors));
});

test('a missing book is a valid problem', async () => {
  const res = await fetch(new URL('books/does-not-exist', API));
  assert.equal(res.status, 404);
  assert.match(res.headers.get('content-type'), /^application\/problem\+json/);
  assert.ok(problem(await res.json()), ajv.errorsText(problem.errors));
});
$ API=http://localhost:8080/ node --test test/
✔ the discovery document has the right shape (14.4ms)
✔ a missing book is a valid problem (6.1ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

In Python tests

With jsonschema (pip install jsonschema) and pytest, or any runner that calls test_* functions.

# test/test_restep.py
import json, os, pathlib, urllib.request, urllib.error
from jsonschema import Draft202012Validator, FormatChecker

API = os.environ.get("API", "http://localhost:8080/")
HERE = pathlib.Path(__file__).parent

def schema(name):
    s = json.loads((HERE / "schema" / f"{name}.json").read_text())
    return Draft202012Validator(s, format_checker=FormatChecker())

def get(path):
    try:
        with urllib.request.urlopen(API + path) as r:
            return r.status, json.load(r)
    except urllib.error.HTTPError as e:
        return e.code, json.load(e)

def test_discovery():
    schema("discovery").validate(get("")[1])

def test_not_found_is_a_problem():
    status, body = get("books/does-not-exist")
    assert status == 404
    schema("problem").validate(body)

To see every mistake at once instead of the first, loop over iter_errors:

for e in schema("discovery").iter_errors(doc):
    print("/".join(map(str, e.absolute_path)) or "/", e.message)
collections/books/filter '_secret' does not match '^[A-Za-z][A-Za-z0-9_-]{0,63}(\\.[A-Za-z][A-Za-z0-9_-]{0,63})*$'
collections/books/filter/price/type 'money' is not one of ['string', 'integer', 'number', 'decimal', 'boolean', 'date', 'datetime', 'duration', 'enum']
collections/books/filter/price/ops/1 'like' is not one of ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'in', 'null']
profiles ['core', 'sync'] does not contain items matching the given schema

In VS Code

If your discovery document is a file in the repository, map it in .vscode/settings.json for completion, hover descriptions and squiggles. Do not add a "$schema" member to the document: the schema only lets through Restep’s members and x- ones, so it would fail. This also works for sample error bodies:

{
  "json.schemas": [
    { "fileMatch": ["**/discovery.json"], "url": "https://restep.wubytes.com/1/schema/discovery.json" },
    { "fileMatch": ["**/errors/*.json"], "url": "https://restep.wubytes.com/1/schema/problem.json" }
  ]
}

With any other validator

# check-jsonschema (pipx install check-jsonschema)
curl -s https://api.example.com/ > discovery.json
check-jsonschema --schemafile https://restep.wubytes.com/1/schema/discovery.json discovery.json

restep-check --schema

npx restep-check --schema <discovery|problem> <file|url|->... [--json]
PartWhat it does
discovery, problemWhich schema. Required
fileA JSON file on disk. Several in one go are fine
urlFetched with GET and Accept: application/json, with no other headers: for a protected API, fetch it with curl -H and pipe it
-Reads standard input
--json{ version, schema, results: [{ document, valid, errors: [{ path, message }], rules: [{ id, status, level, section, target, message }], conforms }] }: valid is the schema, rules the rules of the text (empty with problem) and conforms that neither fails

With discovery, after the schema it runs the rules of the text that the schema cannot express and that need no request: the discovery.* checks of restep-check (except those that look at the response: discovery.present, discovery.same and discovery.service-doc) and, if the document declares query, query.filter.lists and query.language.declared. The report gives the schema and the rules apart. It exits with 0 when every document is valid and breaks no MUST, 1 when one does, and 2 when it cannot run. This mode needs Ajv: npx restep-check brings it; the single file finds ajv and ajv-formats installed next to it or in the folder you run it from (npm install ajv ajv-formats there), and without them says what is missing and the npx command to use.

Limits

  • No schema for collection responses, items or :changes: their shape depends on each API’s fields. Each collection’s own schemas in discovery cover its items (4.3).
  • Profile and extension names are not checked against a list, so a typo such as "qeury" passes. restep-check lists unknown ones in its output, as skipped.

restep-check

The conformance checker. 192 checks against your running API, each one with its section of the specification. Safe in production, made for CI.

· restep-check on npm

All the tools