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/openapiThe package has a peer dependency on @crustjs/core and uses the runtime's global fetch.
apiCommand(options)
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 --listandapi --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
defaultexport), fails withapi: cannot load the OpenAPI document (<reason>)and exit code 1. - The signal's reason or an
AbortErroris 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 sharedparameters. - For an
operationId, the operation with itsmethodandpathadded, and with the path item's sharedparametersmerged into its own: an operation parameter with the samenameandinreplaces the shared one. - An unknown target fails with exit code 1, and so does an
operationIdseveral operations share, naming theirMETHOD paths; pass the path instead.
Both read the spec this way:
- A path item that is itself a local
$ref(such as tocomponents.pathItems) is followed. - Keys of
pathsthat do not start with/, such asx-*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 asdescription. -
A target used more than once, or recursively, keeps its
$refs and is written once under a top-level$refsobject, keyed by the$reftext:{ "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 eachapi <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.
| Flag | Behavior |
|---|---|
-X, --method | HTTP method. Default: GET, or POST when fields or a body are given. See methods |
-F, --field key=value | Repeatable. 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 |
--paginate | Fetches every page through the paginate option, printing each body as one JSON line |
- Fields form a JSON object body. For
GETandHEAD, or when--bodyis given, they become query parameters instead. - A body is sent with
Content-Type: application/jsonunless 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 patchsendsPATCH. - An empty value or one with spaces or other characters, such as
-X "DELETE ", fails with aPARSEerror before any request. - So does a method the runtime's
fetch()would not send, naming what it would send instead: one Node'sfetch()forbids, such asCONNECT, or, on Bun, one it does not know, which itsfetch()would send asGET.
--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
initreuses 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 -scollects the pages into one array, likegh api --paginate --slurp. (Without--slurp,gh apiinstead 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
paginatereturns the request just sent (same resolved URL and method, without a newinit), it fails with exit code 1 instead of looping. Pages already printed stay printed. - Without a
paginateoption,--paginatefails 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 aPARSECrustErrornaming 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
--paginatepages may leave the origin. They must behttp:orhttps:URLs, and are sent there withoutAuthorization,Cookie,Proxy-Authorization, or any header named like anauthheader, 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, somy-cli api /export.zip > export.zipworks and a text body keeps its line endings. - To a terminal, and when output is captured as text, such as by
run()orcaptureExecute(), 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, asgh apiandcurlrefuse to print binary to a terminal; a non-2xx one is left out, and the command fails with theApiResponseError.
| Failure | Result |
|---|---|
| Non-2xx response | The 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 --body | A 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| Command | Result on stdout |
|---|---|
api --list | An 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> --paginate | NDJSON: 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
detailshold thestatus. - JSON numbers are read as JavaScript numbers, so digits beyond double precision are lost and
-0becomes0. Without--json, the body is printed exactly, and--paginatepages 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
pathoff the base URL's origin rejects with aTypeErrorbefore any request. - It adds the
authheaders the request does not set itself. - It passes the invocation's cancellation signal unless
init.signalis given. - With
init.auth: false, for a public operation, neither the request nor its redirects callauthor carry its headers. Untilauthhas run in the invocation its header names are unknown, so onlyAuthorization,Cookie, andProxy-Authorizationare 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:andhttps:targets only, at most 20 redirects per request, counted across origins.301and302turn aPOST, and303any method butGETandHEAD, into a bodylessGET.- A redirect to another origin continues without
Authorization,Cookie,Proxy-Authorization, or any header named like anauthheader, even when the request set its value. - After a redirect, the response (and its
clone()) reportsredirectedastrueandurlas 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: falserequests, and not forapi --listorapi --spec. - It receives the Context setup input, including
signal,stdout, andstderr. - Besides credentials, it may return any default headers, such as
User-Agentor 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.