Crust logoCrust

OpenAPI

Call a CLI's HTTP API and browse its OpenAPI spec from an api command

@crustjs/openapi gives a CLI backed by an HTTP API a gh api-style escape hatch. <cli> api browses the OpenAPI document bundled with the CLI, offline, and sends authenticated requests to any endpoint, including ones no command wraps yet. Your own commands can use the same client as a Context.

Install

npm install @crustjs/openapi

The package has a peer dependency on @crustjs/core and uses the runtime's global fetch.

apiCommand(options)

cli.ts
import { Crust, defineCommand } from "@crustjs/core";
import { apiClient, apiCommand } from "@crustjs/openapi";

// Usually the API's OpenAPI document: `import spec from "./openapi.json" with { type: "json" }`.
const spec = {
	openapi: "3.1.0",
	info: { title: "Example API", version: "1.0.0" },
	paths: {
		"/users": { get: { operationId: "listUsers", summary: "List users" } },
	},
};

const app = new Crust("my-cli")
	.extend(
		apiCommand({
			spec,
			baseUrl: "https://api.example.com/v1",
			auth: () => ({ Authorization: `Bearer ${process.env.EXAMPLE_TOKEN}` }),
			// The next page from a `Link: <url>; rel="next"` header; undefined after the last page.
			paginate: (response) => {
				const next = /<([^>]+)>;\s*rel="next"/.exec(response.headers.get("link") ?? "")?.[1];
				return next === undefined ? undefined : { path: next };
			},
		}),
	)
	.add(
		// App commands share the same base URL and auth through the `api` Context.
		defineCommand("whoami", { description: "Print the signed-in user" }, (command) =>
			command.use(apiClient).action(async ({ ctx, stdout }) => {
				const api = await ctx.api;
				const response = await api.fetch("/me");
				stdout(((await response.json()) as { login: string }).login);
			}),
		),
	);

await app.execute();

apiCommand() provides the apiClient Context and contributes one api command. apiCommand.id is the Extension identity.

Prop

Type

Spec loading

Pass the OpenAPI document as an object, typically a bundled JSON import: it matches the CLI's version, and --list and --spec work offline without a token. To keep a large document out of startup, pass a loader instead:

apiCommand({
  spec: async () => (await import("./openapi.json", { with: { type: "json" } })).default,
  baseUrl: "https://api.example.com/v1",
});
  • The loader runs only for api --list and api --spec, once per invocation.
  • It receives the invocation's signal, so it may also fetch the document from a URL with your own caching and error policy.
  • A loader that throws, or returns anything but a plain object (such as the module namespace instead of its default export), fails with api: cannot load the OpenAPI document (<reason>) and exit code 1.
  • The signal's reason or an AbortError is rethrown unchanged, as cancellation.

Browse the spec

$ my-cli api --list
GET /users listUsers List users
$ my-cli api --spec listUsers
{"method":"GET","path":"/users","operationId":"listUsers","summary":"List users"}

--list prints one line per operation: METHOD path operationId summary, leaving out an operationId or summary the spec lacks. Under --json it prints a JSON array of { method, path, operationId?, summary? } objects instead, which an agent can read without guessing where a summary starts.

--spec <operationId|path> prints one line of JSON:

  • For a path such as /users/{id}, the path item, including its shared parameters.
  • For an operationId, the operation with its method and path added, and with the path item's shared parameters merged into its own: an operation parameter with the same name and in replaces the shared one.
  • An unknown target fails with exit code 1, and so does an operationId several operations share, naming their METHOD paths; pass the path instead.

Both read the spec this way:

  • A path item that is itself a local $ref (such as to components.pathItems) is followed.
  • Keys of paths that do not start with /, such as x-* extensions, are skipped.

--spec resolves local JSON Pointer $refs (#/..., URI-encoded or not), writing each target once, so the output stays as small as the spec, even for large public specs with schemas shared across thousands of places:

  • A target used once in the output replaces its $ref, keeping sibling keys such as description.

  • A target used more than once, or recursively, keeps its $refs and is written once under a top-level $refs object, keyed by the $ref text:

    {
      "method": "POST",
      "path": "/users",
      "requestBody": {
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User" } } }
      },
      "$refs": {
        "#/components/schemas/User": {
          "type": "object",
          "properties": {
            "friends": { "type": "array", "items": { "$ref": "#/components/schemas/User" } }
          }
        }
      }
    }
  • Other $refs, such as external files, #anchor, or a pointer to nothing, stay as is.

Send requests

my-cli api /users                                  # GET
my-cli api /users -F name=ada -F admin=true        # POST {"name":"ada","admin":true}
my-cli api /users -X GET -F page=2                 # GET /users?page=2
my-cli api /users/42 -X PATCH --body @patch.json   # body from a file; - reads stdin
my-cli api /users -H 'Accept: application/vnd.example+json'
my-cli api /users --paginate                       # every page, one JSON line each

api <path> resolves path below baseUrl, keeping the base URL's own path; an absolute URL is used as is. Without <path>, --list, or --spec, it fails with a VALIDATION error.

FlagBehavior
-X, --methodHTTP method. Default: GET, or POST when fields or a body are given. See methods
-F, --field key=valueRepeatable. true, false, null, and JSON numbers become JSON values; anything else, such as 007, stays a string. A number too large for a double, such as 1e309, is rejected
--body <value>Request body: inline, @path (relative to the working directory), or - for all of stdin. Stdin already read to the end, such as by --input - from the input() Extension, is an empty body
-H, --header 'Key: Value'Repeatable request header. Overrides the auth header of the same name
--paginateFetches every page through the paginate option, printing each body as one JSON line
  • Fields form a JSON object body. For GET and HEAD, or when --body is given, they become query parameters instead.
  • A body is sent with Content-Type: application/json unless a header sets it.

Methods

-X takes an HTTP method token (RFC 9110): letters, digits, and !#$%&'*+-.^_`|~.

  • The method is sent in upper case whatever its case, so -X patch sends PATCH.
  • An empty value or one with spaces or other characters, such as -X "DELETE ", fails with a PARSE error before any request.
  • So does a method the runtime's fetch() would not send, naming what it would send instead: one Node's fetch() forbids, such as CONNECT, or, on Bun, one it does not know, which its fetch() would send as GET.

--paginate

After each successful page, --paginate calls paginate(response) with a copy of the response, so it may read headers or the body. It requests the page paginate returns, until it returns undefined.

  • A returned request without init reuses the previous request's method, headers, and body.
  • Each page body is printed as one JSON line (NDJSON), so my-cli api /users --paginate | jq -s collects the pages into one array, like gh api --paginate --slurp. (Without --slurp, gh api instead joins array pages into one array.) JSON is compacted by removing whitespace outside strings, so numbers keep their exact digits; any other text body, including an empty one, is printed as a JSON string. A page body that is not valid UTF-8 has no JSON line, so it fails the command with exit code 1; pages already printed stay printed.
  • If paginate returns the request just sent (same resolved URL and method, without a new init), it fails with exit code 1 instead of looping. Pages already printed stay printed.
  • Without a paginate option, --paginate fails before any request.

Origins and credentials

Like gh api, the request must stay on the base URL's origin (scheme, host, and port, after URL normalization), so credentials never reach a host given on the command line.

  • An absolute URL to another origin, including tricks such as https://api.example.com@evil.example, fails with a PARSE CrustError naming the URL and the allowed origin, before any request.
  • .. segments may leave the base URL's path: the boundary is the origin, not the path prefix.
  • Only redirects and --paginate pages may leave the origin. They must be http: or https: URLs, and are sent there without Authorization, Cookie, Proxy-Authorization, or any header named like an auth header, including values set with -H.

Output and errors

The response body goes to stdout:

  • To a pipe or file, the body is written as its exact bytes, whatever its Content-Type, so my-cli api /export.zip > export.zip works and a text body keeps its line endings.
  • To a terminal, and when output is captured as text, such as by run() or captureExecute(), the body is printed as text, ending with exactly one newline; an empty body prints nothing. A body that is not valid UTF-8 can't be printed as text and fails the command with exit code 1 after the request, as gh api and curl refuse to print binary to a terminal; a non-2xx one is left out, and the command fails with the ApiResponseError.
FailureResult
Non-2xx responseThe body still prints to stdout, then an ApiResponseError (exit 1) whose status holds the code; its message, such as GET /users/9: HTTP 404 Not Found, goes to stderr
-F without = or out of number range, -H without : or with a name or value HTTP rejects, an invalid -X, unreadable --bodyA PARSE CrustError before any request

The -F and -H errors name the flag and the expected shape, such as Invalid -H value: expected "Name: value"., never the text given, since a header can hold a token. For the same reason, an ApiResponseError leaves out the request's query and fragment, including query parameters -F added: its message shows the path as given up to its ?.

JSON output

With the json() Extension registered, --json makes api return its data as the command result, so stdout carries only JSON:

$ my-cli api /users/42 --json
{"id":42,"name":"Ada"}                                     # stdout
$ my-cli api /users/9 --json
{"message":"not found"}                                    # stderr: the response body
{"message":"GET /users/9: HTTP 404 Not Found","details":{"status":404}}   # stderr
CommandResult on stdout
api --listAn array of { method, path, operationId?, summary? }
api --spec <target>The definition --spec prints, as above
api <path>The response body: parsed when it is JSON, otherwise its text as a JSON string; nothing for an empty body. A body that is not UTF-8 fails the command, since JSON can't hold it
api <path> --paginateNDJSON: one {"type":"event","data":…} line per page with its body as above (an empty body is ""), then {"type":"result"}, or {"type":"error","error":…} for a failing page
  • A non-2xx body is written to stderr, followed by the error JSON, whose details hold the status.
  • JSON numbers are read as JavaScript numbers, so digits beyond double precision are lost and -0 becomes 0. Without --json, the body is printed exactly, and --paginate pages keep their exact digits.

apiClient

The api Context: a fetch() bound to the base URL and auth. apiCommand() provides it to every command, so a command declares it with .use(apiClient) and calls (await ctx.api).fetch(path, init?), as whoami does above.

Prop

Type

fetch(path, init?)

Resolves path like api <path> and returns the Response.

  • A path off the base URL's origin rejects with a TypeError before any request.
  • It adds the auth headers the request does not set itself.
  • It passes the invocation's cancellation signal unless init.signal is given.
  • With init.auth: false, for a public operation, neither the request nor its redirects call auth or carry its headers. Until auth has run in the invocation its header names are unknown, so only Authorization, Cookie, and Proxy-Authorization are stripped from such a request on another origin.

Unless init.redirect is "manual" or "error", fetch() follows redirects itself, with the global fetch()'s rules:

  • http: and https: targets only, at most 20 redirects per request, counted across origins.
  • 301 and 302 turn a POST, and 303 any method but GET and HEAD, into a bodyless GET.
  • A redirect to another origin continues without Authorization, Cookie, Proxy-Authorization, or any header named like an auth header, even when the request set its value.
  • After a redirect, the response (and its clone()) reports redirected as true and url as the final URL.

auth(input)

  • It runs at most once per invocation, on the first request that sends credentials: not when a command reads the Context, not for auth: false requests, and not for api --list or api --spec.
  • It receives the Context setup input, including signal, stdout, and stderr.
  • Besides credentials, it may return any default headers, such as User-Agent or an API-version header. All of them are treated as credentials, so they go only to the base URL's origin.

Out of scope

@crustjs/openapi does not generate one command per operation, filter output (--jq), or template endpoint paths. Write commands for the operations that deserve them, with apiClient for the request.

On this page