Restep2½

Tools · Use an API · v0.2.0

restep (CLI)Your API, in the shell

A command line client that learns the API from its discovery document. It checks your filters before sending them, follows every page, and completes collections and fields in zsh and bash.

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

Why use it

It knows your API

It reads the discovery document first. A collection, filter, operator, sort key or value that does not exist is rejected on your machine, with a “did you mean…?”, before a single request leaves.

Every page, any format

--all follows next to the end. Tables in the terminal, JSON in a pipe, and NDJSON or CSV when you ask, ready for jq or a spreadsheet.

Writes that do not bite

create sends an Idempotency-Key by itself, so running it twice does not create twice. --safe reads the ETag and writes with If-Match.

Tab completes your API

In zsh and bash: commands, collections, filters, enum values, sort keys and fields, read from discovery. Node 18, no dependencies.

How it works

  1. It works out which API you mean: the URL in the first argument, an @alias from your config, RESTEP_URL, or the default alias.
  2. It reads the discovery document at the root, or the one linked with rel="service-desc". It keeps a copy in a local cache for as long as max-age says, 300 seconds at most, and revalidates it with If-None-Match.
  3. It checks your request against it: collection, methods, filters with their type and operators, sort, fields, limit up to max_limit, and the body against the create, update or action input schemas when they are embedded. If something is wrong it stops with exit code 3 and says why. If the rejection came from the cached copy, it fetches discovery again before giving up, in case the API changed.
  4. It sends the request, with the headers the specification asks for: application/merge-patch+json on PATCH, an Idempotency-Key on POST, If-Match when you ask for it.
  5. It prints the result, or the problem+json in readable form on stderr with a hint of what to do, and leaves with an exit code that says what happened.

For now its messages, its help and its column headings are in Spanish. Commands, options, field names and the JSON it prints are the same in any language.

Install

You need Node 18 or later and nothing else: the package has no dependencies. Install it globally to get the restep command, which completion needs:

npm install -g restep-cli
restep https://demo.restep.wubytes.com/       # what does this API offer?
restep --version

To try it once without installing anything: npx restep-cli https://demo.restep.wubytes.com/.

Every example on this page runs against the public demo API, a bookshop with books, products in several languages and nested categories.

Examples

See what an API offers

$ restep https://demo.restep.wubytes.com/
Restep 1.0-draft.6 · versión 1 de la API · https://demo.restep.wubytes.com/
Perfiles: core, query, writes, cache
Extensiones: actions
Estado del servicio: /health

colección   ruta         métodos                                descripción
----------  -----------  -------------------------------------  ------------------------------------------------------------
books       /books       GET POST · elemento: GET PATCH DELETE  Books in the catalogue of El Marcapáginas, one per edition.
products    /products    GET POST · elemento: GET PATCH DELETE  Other products of the shop, with their name and description…
categories  /categories  GET POST · elemento: GET PATCH DELETE  Product categories, nested.

Recursos sueltos (§5.9; get y update sin id):
recurso  ruta   métodos    descripción
-------  -----  ---------  -----------------------
shop     /shop  GET PATCH  The shop’s own details.

Without a command, restep <url> is describe. With a collection, it lists filters with their type, operators and values, named filters, sort keys, page size, fields, required fields and defaults on create, who picks the id, collations, the parent of a subcollection, language maps, relations, inherited fields and actions:

$ restep https://demo.restep.wubytes.com/ describe books
books  /books
  Books in the catalogue of El Marcapáginas, one per edition.
  Métodos: GET, POST; elemento: GET, PATCH, DELETE
  Filtros:
    campo         tipo      operadores          valores                                                  descripción
    ------------  --------  ------------------  -------------------------------------------------------  -----------
    id            string    eq, in
    price         decimal   eq, lt, le, gt, ge
    category      enum      eq, ne, in          novela-negra, ciencia-ficcion, ensayo, poesia, infantil
    year          integer   eq, lt, le, gt, ge
    rating        number    ge, null
    published     date      lt, ge
    reading_time  duration  le, gt
    signed        boolean   eq, null
  Filtros con nombre (sin operadores; -f nombre o -f nombre=valor):
    nombre   valor                  valores  descripción
    -------  ---------------------  -------  --------------------------------------------
    bargain  ninguno (interruptor)           Under 15 euros and rated 4 or more.
    search   string                          Title contains the text, case-insensitively.
  Orden: id, title, price, rating, year, published
  Página: max_limit 50 · count exact
  Campos: id, title, price, category, year, published, reading_time, rating, signed
  Obligatorios al crear: title, price
  Por defecto al crear: category="novela-negra", signed=false
  Acción new (colección, GET, segura, idempotente): The body of a POST already filled in for this client, to start a form; it creates nothing.

Query a collection

$ restep https://demo.restep.wubytes.com/ get books -f category=novela-negra -s -price
id  title                     price  category      year  published   reading_time  rating  signed
--  ------------------------  -----  ------------  ----  ----------  ------------  ------  ------
7   La niebla de Portugalete  18.50  novela-negra  2025  2025-03-14  PT6H          4.6     true
12  El último ferry           16.90  novela-negra  2023  2023-10-02  PT5H30M       4.3
15  Lluvia sobre Deusto       14.95  novela-negra  2022  2022-05-20  P1DT2H        4.1     false

$ restep https://demo.restep.wubytes.com/ get books -f 'price<=15' --fields title,price --all -o csv
id,title,price
15,Lluvia sobre Deusto,14.95
30,Cuaderno de faros,9.00
50,Bajo la niebla,11.90

$ restep https://demo.restep.wubytes.com/ get books --count
7

In a terminal a list comes out as a table, and in a pipe as JSON, so restep … get books | jq just works. Without --all you get one page, and if there are more it says so on stderr with the next link.

Mistakes caught before sending

$ restep https://demo.restep.wubytes.com/ get books -f category=novela-negr
restep: Filtro category[eq]: «novela-negr» no es un valor admitido.
  ¿Quisiste decir «novela-negra»?
  Valores: novela-negra, ciencia-ficcion, ensayo, poesia, infantil.
  (rechazado antes de enviar; --raw lo envía igual)
$ echo $?
3

$ restep https://demo.restep.wubytes.com/ get books -s author
restep: La colección «books» no se puede ordenar por «author».
  Orden: id, title, price, rating, year, published.
  (rechazado antes de enviar; --raw lo envía igual)

$ restep https://demo.restep.wubytes.com/ get books -n 80
restep: --limit 80 supera el máximo de «books», 50.
  (rechazado antes de enviar; --raw lo envía igual)

$ restep https://demo.restep.wubytes.com/ create books -d '{"title":"Sin precio"}'
restep: El cuerpo no cumple el esquema create de «books»:
  /price (required): es obligatorio.
  (rechazado antes de enviar; --raw lo envía igual)

--raw sends it anyway. Then it is the server that answers, and the CLI shows its error with a hint. Here the reference server, which does not offer an author filter:

$ restep http://localhost:8080/ get books -f author=Pérez --raw
Error 400 unsupported_parameter: Bad request
  This resource does not support filter[author].
  Parámetro: filter[author]
  Pista: filtros de «books»: id (eq, in); price (eq, lt, le, gt, ge); category (eq, ne, in); year (eq, lt, le, gt, ge); rating (ge, null); author.id (eq, in); author.name (eq, in); con nombre: featured, search.
  Pista: la API no ofrece eso: no sirve reintentarlo.
$ echo $?
5

Include relations

The demo does not announce relations; the reference server does (Perfiles: core, query, writes, cache, relations), with authors, reviews as a subcollection of each book, and to-one, to-many and polymorphic relationships. -i asks for include (§9) and is checked before sending:

$ restep http://localhost:8080/ describe books
books  /books
  Books in the catalogue of El Marcapáginas, one per edition.
  ⋮
  Relación author → authors · include
  Relación related → books (a muchos) · include
  Relación highlight → reviews · include

$ restep http://localhost:8080/ get books -i author --fields title,author -n 2 -o json
{
  "items": [
    {
      "id": "12",
      "title": "El último ferry",
      "author": {
        "id": "2",
        "name": "Jon Uriarte",
        "country": "ES"
      },
      "_etag": "\"3f229ea9fc9865da\""
    },
    ⋮
  ],
  "next": "/books?fields=title%2Cauthor&include=author&limit=2&cursor=…"
}

$ restep http://localhost:8080/ get books -i author.books
restep: «author.books» pasa de la profundidad de include de «books» (1) (§9).
  (rechazado antes de enviar; --raw lo envía igual)

$ restep http://localhost:8080/ get shop -i owner
restep: «shop» es un recurso suelto: no admite include (§5.9).
  (rechazado antes de enviar; --raw lo envía igual)

Write without duplicating or overwriting

$ restep http://localhost:8080/ create books -d '{"title":"Faro de Gorliz","price":"12.00","category":"poesia"}' --idempotency-key faro-1
{
  "title": "Faro de Gorliz",
  "price": "12.00",
  "category": "poesia",
  "id": "100",
  "_etag": "\"e112db851596f878\""
}
$ restep http://localhost:8080/ create books -d '{"title":"Faro de Gorliz","price":"12.00","category":"poesia"}' --idempotency-key faro-1
(repetición: la API devuelve la respuesta guardada para esta Idempotency-Key)
{
  "title": "Faro de Gorliz",
  ⋮
  "id": "100",
  "_etag": "\"e112db851596f878\""
}

$ restep http://localhost:8080/ update books 100 -d '{"price":"13.50"}' --safe
{
  "title": "Faro de Gorliz",
  "price": "13.50",
  "category": "poesia",
  "id": "100",
  "_etag": "\"ab8400e4825c77a6\""
}

$ restep http://localhost:8080/ update books 100 -d '{"price":"14"}' --if-match '"viejo"'
Error 412 precondition_failed: The resource has changed
  Someone changed it: read it again before writing.
  Pista: alguien ha cambiado el elemento: vuelve a leerlo, o usa --safe.
$ echo $?
8

The second create with the same key creates nothing: the API returns the stored response and the CLI warns on stderr. Without --idempotency-key each create gets a fresh random key (only if the API announces writes).

See the request, or send it with curl

$ restep http://localhost:8080/ update books 100 -d '{"price":"14"}' --safe --curl
# --safe: primero se lee el ETag actual
curl -sS 'http://localhost:8080/books/100' -H 'accept: application/json, application/problem+json'
curl -sS -X PATCH 'http://localhost:8080/books/100' -H 'accept: application/json, application/problem+json' -H 'content-type: application/merge-patch+json' -H 'if-match: <ETag del GET anterior>' --data-raw '{"price":"14"}'

--curl prints and sends nothing. The token never appears: the curl reads it from $RESTEP_TOKEN. -v sends the request and writes every request and response with their headers to stderr, with the token as Bearer ****.

Commands

The shape is always restep [<url> | @alias] <command> [arguments] [options].

CommandRequest
describe [collection|resource]GET of the root. Without a name: version, profiles, extensions, status, collections and singletons. With a collection: its filters and named filters, sort, page, fields, required fields and defaults on create (§4.3), id_from, collations, parent, language maps, relations, inherited fields and actions. The default command
get <collection>GET of the collection: one page, or all with --all
get <collection> <id>GET of the item
get <resource>GET of a singleton (§5.9), such as /me, without an id; takes --fields
update <resource> --data …PATCH of a singleton, without an id. create, delete and action on a singleton are rejected before sending
create <collection> --data …POST, with a random Idempotency-Key if the API announces writes
update <collection> <id> --data …PATCH with application/merge-patch+json. A patch with a different id is rejected before sending
delete <collection> <id>DELETE
action <collection> [<id>] <name>POST /collection/id:name or /collection:name; GET if the action declares it (§11.1). Non-idempotent actions get an Idempotency-Key; without --data the body is {}
completion zsh|bashPrints the completion script. No URL

In a subcollection, such as /books/{book_id}/reviews, give the id of each parent with -p, in order: restep … get reviews -p 7.

Filters, sort and fields

Each -f is one filter (§6.1); several combine with AND. Quote them, or the shell will take < and > as redirections.

You writeIt sends
-f category=poesiafilter[category]=poesia
-f 'year[ge]=2020'filter[year][ge]=2020, any declared operator
-f 'category!=poesia'filter[category][ne]=poesia
-f 'price<10', 'price<=10'[lt], [le]
-f 'year>2020', 'year>=2020'[gt], [ge]
-f 'category[in]=poesia,ensayo'A list, separated by commas
-f 'rating[null]=true'Absent or null; false for “has a value”
-f name.es-mx=GomaOne translation of a language map, as discovery declares it
-f bargain, -f search=nieblaA named filter (§6.1), without an operator: filter[bargain]=, with no value, if it is a switch, filter[search]=niebla if it takes a value. describe lists them with their description

Before sending, it checks that the field and the operator are declared, that the value fits the type (integer, number, decimal, boolean, date, datetime, duration without years or months, enum with its values), that null gets true or false, that an in is not empty and that no filter appears twice.

-i author,category.parent includes relationships (§9): only those declared with "include": true, up to include_depth, with a polymorphic one only at the end of the path.

-s -rating,title sorts (§6.2): a - in front is descending. --fields title,price asks for only those fields (§6.3), also when getting one item. -n sets the page size, up to max_limit (§6.4). --count prints only the total (§6.5): it sends count=true and limit=1; with -o json it prints {"total": N}, plus total_estimated if the API only estimates it.

Output formats

-oWhat you get
tableAligned columns, one per field, cells cut at 40 characters. An item becomes a field and value table. The default for lists in a terminal
jsonThe response as it came, indented: {items, next} for a page, the item for an item. With --all, every item in one {items, next: null}. The default in a pipe, and for single items
ndjsonOne item per line. With --all it writes each page as it arrives, so it suits large collections
csvA header row and one row per item

table and csv leave out members that start with _ and write objects as JSON. A write answered without a body, as with --minimal, prints status, location and etag instead.

Options

OptionWhat it does
-f, --filter field=valueA filter, or a named filter (-f name or -f name=value). Repeatable. Syntax above
-s, --sort -field,fieldSort keys; - is descending
--fields a,bOnly those fields (lists and items)
-i, --include rel,rel.relIncludes relationships (§9), on the collection and on an item. Each step is a relationship declared with "include": true, no deeper than include_depth (1 if not declared); a relationship to several collections (to as a list) can only come last in the path. Not allowed on a singleton (§5.9)
-n, --limit NPage size. With --all, the size of each page
--allFollows next as it is until null (§5.2). Stops if a page repeats
--countOnly the total
-o, --format json|ndjson|csv|tableOutput format
-d, --data '<json>' | @file | -The body; - reads standard input
--if-match <etag>Writes only if the item has not changed. With or without quotes
--safeReads the item first and writes with If-Match set to its _etag or, failing that, its strong ETag header (§7.2). Not together with --if-match
--idempotency-key <key>Your own key instead of a random one (§7.1). Visible ASCII, no quotes or backslashes
--minimalSends Prefer: return=minimal (§7.3)
--retry NRetries network errors, 429, 502, 503 and 504 (and 409 with a key: the same request still running), honouring Retry-After up to 30 s. Only reads, DELETE and requests with an Idempotency-Key, the ones that can be repeated safely
-p, --parent <id>The id of a parent in a subcollection. Repeatable, in order
-H, --header 'Name: value'An extra header. Repeatable
--token <token>Bearer token. Also RESTEP_TOKEN or the alias
--language <tag>Sends Accept-Language (§5.6). Also RESTEP_LANGUAGE or the alias
--rawSkips every local check and sends anyway. A collection missing from discovery becomes /<collection>
--no-cacheFetches discovery again
-v, --verboseEach request and response with its headers, on stderr
--curlPrints the equivalent curl and sends nothing
-h, --help, --versionHelp and version

Aliases, tokens and language

So you do not type the URL every time, give your APIs a name in ~/.config/restep/config.json (or $XDG_CONFIG_HOME/restep/config.json, or the path in RESTEP_CONFIG):

{
  "default": "shop",
  "aliases": {
    "shop": { "url": "https://api.shop.example/v1/", "token_env": "SHOP_TOKEN", "language": "es" },
    "demo": "https://demo.restep.wubytes.com/"
  }
}
restep @demo get books -f category=poesia
restep get orders -f status=paid          # no URL: RESTEP_URL, or the default alias

The API comes from the first argument, then RESTEP_URL, then the default alias. The token, from --token, then the alias (token, or token_env with the name of an environment variable), then RESTEP_TOKEN. The language, from --language, the alias or RESTEP_LANGUAGE.

Credentials only go to the API’s origin (§4.3): a next or a link to another origin is fetched without them.

Discovery is cached in ~/.cache/restep/ (or $XDG_CACHE_HOME/restep/, or RESTEP_CACHE_DIR), one file per API, language and token. Of the token it only keeps a hash. A no-store response is not kept.

Completion in zsh and bash

It needs restep on your PATH (see Install). Then add one line to your shell’s config file and open a new terminal:

# ~/.zshrc, after compinit
eval "$(restep completion zsh)"

# ~/.bashrc
eval "$(restep completion bash)"

It suggests commands, aliases, collections, filters (field= and field[op]=), enum values (also inside an in), sort keys with and without -, fields for --fields, formats, options and actions. It reads them from discovery, using the cached copy for up to 300 seconds even if it has expired, and if it has to fetch it waits 2 seconds at most. On the demo, after get books -s, Tab offers id, -id, title, -title, price, -price and so on; after -f 'category[in]=poesia,', the other categories.

What it does as a draft 6 client

What §12.2 asks of a client, and how the CLI does it:

  • Version (§1.1). It accepts restep with a suffix (1.0-draft.6, 1.0-rc.1) and shows it in describe. A discovery document whose restep does not follow the grammar, or whose major version is not 1, is not Restep 1: the CLI stops with exit code 1, also with --raw or --curl, instead of assuming just core.
  • Experimental parts (§1.2). The only one it uses is inherit (the own-field hint and the inherited fields in describe), and only if the API announces the extension and declares "restep": "1.0-draft.6", the text it knows. With another version, describe warns and leaves it alone. It never uses sync, batch, filter-expr or query-method.
  • Unknown values (§4.2). A filter or named filter with a type it does not know, an operator outside the list of §6.1, and an action with an on or a method it does not know are treated as not declared: describe points them out, validation rejects them and completion does not offer them.
  • Singletons (§5.9). get and update without an id; create, delete and action are rejected locally. A singleton with a template in path or with parent is ignored.
  • id_from (§5.1). With a value it does not know, it sends no id on create (not even with --raw). It also warns locally about an id where the server assigns it, and about a missing one with "client".
  • idempotency.anonymous: false (§7.1). Without credentials (no token, no -H Authorization or Cookie) it adds no random Idempotency-Key, and --idempotency-key is rejected locally.
  • Bodies and queries (§3, §5.2). Content-Type: application/json on create and POST actions, application/merge-patch+json on update. A literal + in a value goes as %2B.
  • Links (§3). It does not follow a next or a service-desc whose scheme is neither https nor the root’s. Credentials, including those passed with -H (Authorization, Cookie, Proxy-Authorization, DPoP), only go to the API’s origin.

Exit codes

So a script can tell a typo from a missing item from a server on fire. Every error also comes out on stderr; with -o json, the problem+json also goes to stdout as it came.

CodeWhen
0All went well
1Anything else: a response that is not Restep, a loop in next…
2Wrong usage: arguments, malformed JSON, an alias that does not exist
3Rejected locally against discovery, nothing sent
4Network error
5400
6401, 403
7404, 410
8409, 412, 428
9422
10Any other 4xx
115xx

Along with the error it gives hints: the filters or sort keys the collection does offer after an unsupported_parameter (and that retrying will not help), the own field after a read_only on an inherited value (§11.6), --safe after a 412, and how to pass the token, plus the OAuth metadata URL, after a 401.

Limits

  • Of relations it only reads (--include): it does not build relationship objects when writing. It does not cover sync, batch, filter-expr or query-method; a filter= expression has no option of its own (you can send one by hand with --raw).
  • It only validates against schemas embedded in discovery: a linked schema is not downloaded. --fields is only checked when there is an embedded schemas.item.
  • It does not check readOnly. Writing the effective field of an inherited value is rejected by the server, and the CLI hints at the own field.
  • Completion does not suggest item ids.
  • There is no OAuth flow: get the token elsewhere and pass it with --token or RESTEP_TOKEN.
  • Of draft 6 it does not do: creating or linking relationships (it builds no relationship objects, so no href for an item of a subcollection either, §5.1); deprecations are only counted in describe (no kind, announced or sunset, and no warning on a Deprecation header), and notices with an unknown kind are counted all the same; collations and parent are only shown; it does not read reasons (a reason is shown as it comes and the exit code follows the status, as §5.4 asks); it does not retry a PATCH, though §5.7 allows it; it does not validate a singleton’s update schema when it is linked; and an item’s _inherited is shown as it comes, without interpreting from.
  • Its messages are in Spanish.

Explorer

Browse any Restep API from this site: query forms built from discovery, writes, actions, errors explained and the curl for every request.

· Open the explorer

restep-sync

An offline-first client: a local replica kept up to date incrementally, writes that queue while offline, and conflicts resolved your way.

· restep-sync on npm

All the tools