
Configure schemas, wrappers, and documentation
Source:vignettes/configuration.Rmd
configuration.RmdUse one project file to select service files. A service combines
local schemas with generation policy. An operation is identified by
service ID, HTTP method, and original schema path.
Names such as GET /items/{item_id} below must match that
path exactly, including trailing slashes.
All project/config/schema paths resolve against the explicit client
root, not the current working directory or the service
YAML’s directory. Use relative paths inside YAML. Parent traversal,
absolute paths, and symlinks are rejected.
JSON and YAML schema files
Pass a local .json, .yaml, or
.yml file directly to read_operations(),
configure_client(), or initialize_client().
The API catalogue, project generation, and schema comparisons use the
same schema loader. No separate conversion command or converted JSON
sidecar is needed. Service schemas.files and
schemas.patterns can select either format. Initialization
keeps the source format and extension in
schema/openapi.<ext> for a single API, or
schema/<api>.<ext> for a reviewed API
catalogue.
YAML uses YAML 1.2 scalar resolution: unquoted yes,
no, on, and off are strings;
true and false are booleans. Quote values when
the schema requires a string, including Swagger’s
swagger: '2.0'. Empty objects ({}), empty
arrays ([]), explicit nulls, and omitted fields remain
distinct. Sequence elements are retained as lists, including
single-element sequences. UTF-8 text is read without depending on the
machine’s locale. Types are never inferred from examples.
Numbers use R’s integer/double representation, as with JSON
ingestion. Values outside the 32-bit integer range use doubles;
arbitrary-precision integers are not supported, and values beyond the
exact double range can lose precision. Non-finite numbers are rejected.
YAML input must contain exactly one document. Duplicate mapping keys,
complex keys, boolean/null keys, and custom tags (including executable
tags) are rejected. Mapping keys must be strings or exact integers with
absolute value at most 2^53 - 1. Integer response keys such
as 200: are read as strings; quoting them is clearer. YAML
anchors and aliases are supported; merge keys (<<)
are rejected.
These rules support the JSON-shaped data model described in the OpenAPI format specification. Local file references resolve relative to the file containing each reference, including references in path items and operations. Remote references are not downloaded. Missing files and unsupported recursive references produce diagnostics when they affect an operation’s request contract. Initialization bundles local dependencies into the copied schema so the generated client does not depend on the original download directory. JSON and YAML share these rules.
Reviewed remote references
Parsing and generation never fetch a remote $ref. To
resolve one, download the target explicitly, review it, and record it in
specmill-references.yml beside the root schema.
freeze_references() does both:
specmill::freeze_references(
'schema/openapi.json',
'https://raw.githubusercontent.com/opengeospatial/ogcapi-records/master/core/openapi/parameters/sortby.yaml'
)It stores the file under
references/<host>/<path> and writes an entry
like this, which you can also write by hand:
references:
- url: https://raw.githubusercontent.com/opengeospatial/ogcapi-records/master/core/openapi/parameters/sortby.yaml
file: references/sortby.yaml
sha256: <sha256 of the reviewed file>
retrieved: 2026-11-05 # optional provenance noteurl is the referenced document without its fragment;
matching is exact. file is relative to the lock file and
must stay inside its directory; JSON or YAML is chosen by its extension.
Compute sha256 with
digest::digest(file = 'references/sortby.yaml', algo = 'sha256').
Relative references inside a mapped document resolve against its
url, not its local path, and must be mapped too. A
malformed lock file stops parsing.
Parsing then works offline and reproducibly. The lock file and mapped files are generation inputs, so check mode reports their hash changes. Initialization bundles them, and the generated client never fetches schemas at runtime.
To refresh a mutable URL, call
freeze_references(..., refresh = TRUE) after reviewing the
upstream change, or replace the file and update its sha256
in the same reviewed change. Without refresh, a changed
upstream stops with both hashes. Nested references are not followed;
freeze each unmapped URL that read_operations() reports.
Until then, changed bytes produce reference_hash_mismatch.
Other per-operation diagnostics: external_reference (URL
not in the lock or not HTTP(S)), unresolved_reference
(mapped file missing), invalid_reference (unreadable file),
recursive_reference, and reference_base (a
mapped schema $id changes the reference base). Unrelated
operations still parse. Keep the lock file next to every copy of the
schema you parse or diff.
Opaque recursive JSON request bodies
An operation whose frozen remote request schema recurses, or uses
$dynamicRef, can explicitly delegate body shape validation
to its server:
operations:
POST /collections/agency-codes/items:
opaque_body:
reference: https://schemas.opengis.net/cql2/1.0/cql2.json
reason: Reviewed CQL2 JSON filters; the server validates their shape.opaque_body belongs under an individual OpenAPI 3
operation. It requires the exact remote reference used by that
operation’s application/json body schema and a nonempty
review reason. The reference must already be frozen through
specmill-references.yml. File existence, SHA-256 checks,
missing dependencies and other reference errors remain enforced.
Initialization preserves the URL and reviewed hash when it bundles these
schemas into the client.
The wrapper accepts JSON-compatible R values without enforcing the referenced schema’s shape. Use named lists for objects and unnamed lists for arrays. Body requiredness, JSON representability, and ordinary parameter validation remain. No request media type, parameter, response, or schema source file is changed. Without the review, recursive references and unsupported dynamic keywords keep their existing diagnostics. Typed dynamic-reference resolution remains unsupported.
Inspect
read_operations(..., policy = list(opaque_bodies = reviews))$body_diagnostics,
where reviews maps method/path keys to the same
reference/reason lists, or
generate_client(..., mode = 'plan')$body_diagnostics. These
informational records do not block generation. Each contains the URL,
reviewed SHA-256, review reason and source location. Generated body
documentation states the validation limit, and wrapper entries in
.specmill/manifest.json retain opaque_bodies
provenance. Ordinary diagnostics remain blocking.
Default schema validation still runs. Its original report is retained
alongside the service’s reviewed validation view. Only the approved
request schemas become opaque in that view; unrelated validation
failures still block generation. validate_schema() alone
has no operation policy and reports the original schema.
Project file: specmill.yml
Schema validation
Generation requires validation by default. Each schema is checked
locally against the official Swagger 2.0, OpenAPI 3.0, 3.1 or 3.2 JSON
Schema; nothing is uploaded. validate_schema() returns a
standalone report. Validation treats empty strings in
info.contact.url and info.contact.email as
omitted and leaves the source file intact. Other values are checked
normally. Explicit validation: false bypasses the gate and
should be a reviewed project decision:
References outside the document return unsupported coverage; bundle
them first, or map remote ones in specmill-references.yml
so validation checks the resolved document. Request mappings and
retained implementations cannot bypass the gate.
Review multiple APIs once
Put the downloaded JSON or YAML schemas in the project root. The API catalogue proposes names from schema titles, detects duplicate content independently of filenames and formatting, and offers one editable table:
apis <- specmill::configure_apis(root, mode = 'apply')Default discovery selects .json, .yaml, and
.yml files directly inside root, excluding
specmill.yml, specmill.yaml,
specmill-apis.yml, and specmill-apis.yaml.
Pass schemas explicitly when other configuration YAML files
share the directory. Equivalent JSON and YAML documents count as
duplicate content.
In an interactive session, review api,
base_url, and include, then close the editor.
Choices are saved in specmill-apis.yml; unchanged inputs
reuse them without prompting again. Use review = TRUE to
revisit choices. In batch scripts, use review = FALSE;
choices accepts a data frame keyed by schema
for scripted name, URL and inclusion overrides. Planning is read-only by
default.
Names come from info.title, with suffixes when distinct
schemas share a title. Relative servers need the download origin: pass
origins, a character vector of URLs named by schema paths
relative to root. Missing/ambiguous servers need explicit base URLs
before saving. Server-variable defaults and Swagger host/basePath
metadata are supported. Incorrect reverse-proxy metadata still requires
review.
Pass the reviewed table as schema to
configure_client() or initialize_client(). The
generated YAML keeps tag grouping within each API, prefixes function
names with its reviewed API name. initialize_client() also
creates a request helper for each included API;
configure_client() only proposes configuration and schema
copies. Credential names use api.scheme, so identical
scheme names in different APIs do not share tokens accidentally. Service
authentication maps refer to these project credential names. Set a
credential with
set_api_token(token, scheme = 'reviewed_api.api_key').
For a new multi-API package, use the reviewed table in the same initialization and generation sequence as a single schema:
# root is an existing directory containing schemas, with no package scaffold yet.
apis <- specmill::configure_apis(root, mode = 'apply')
proposal <- specmill::configure_client(
root, apis, package = 'combinedclient', name_case = 'snake_case'
)
proposal$diagnostics
# After reviewing API names, URLs, inclusion, and proposed function names:
specmill::initialize_client(
root, apis, package = 'combinedclient', title = 'Combined API Client',
author = list(given = 'Example', family = 'Maintainer', email = 'you@example.org'),
license = 'MIT + file LICENSE', name_case = 'snake_case'
)
plan <- specmill::generate_client(root, config = 'specmill.yml', mode = 'plan')
plan$diagnostics
plan$files
# Review, then apply and check as in the new-client guide.Keep specmill-apis.yml in Git alongside the schema
snapshots and reviewed service YAML. For an existing package, stop at
the configuration proposal and follow adoption; initialization would conflict
with its scaffold. Updating the catalogue does not automatically merge
service YAML or refresh client-owned helpers.
Response policy and selected formatting
New request helpers accept response_policy. Select a
retained client function once under project, API/group, or service
defaults:
The name must resolve to a function in client source. YAML contains a
name, never executable R. Operation overrides can select a different
function; response_policy: null removes the generated
selection and restores the helper default. Complete
request.arguments mappings own the entire call and must
pass response_policy explicitly, using a literal function
name binding.
The contract is function(response, context, decode). It
runs once on the final httr2_response, after any retries,
before HTTP errors and decoding. context contains
method, status, and normalized actual response
media. When the request has an input to attribute,
context$query also holds it. That is the items of an array
body (an unnamed list or vector), otherwise the value of the sole path
parameter, otherwise the value of the sole URL query parameter. A query
value is reported even if it is a credential, since it was already sent
in the URL. Headers, cookies, object bodies, and the URL itself are
never included. The response itself can contain sensitive information;
client policy owns its observation and logging. Policies do not run for
dry runs or transport failures without a response.
observe_response <- function(response, context, decode) {
# Call a client-owned observer here, including on 4xx/5xx responses.
decode()
}decode() applies the existing status check and native
JSON/list, text/string, binary/raw, or empty/NULL decoding. Calling it
delegates. Any callback return value, including NULL, is a
replacement result. Warnings and errors propagate. A policy may call
decode(check_status = FALSE) to read a selected error body,
or return a replacement without decoding malformed content. Policies can
retain metadata for a future paginator by returning
list(response = response, result = decode()). Native
defaults do not attach metadata or discard envelope fields.
For direct helper calls, pass a function or a client function name. A
package option such as
options(myclient.response_policy = observe_response)
selects a shared helper default. Its prefix follows the package
request-option prefix. An explicit helper argument overrides that
option, including NULL. Generated YAML selections are
explicit arguments and take precedence over the option. Named functions
resolve in the helper’s enclosing client environment.
For CSV/TSV, select the emitted <helper>_delimited
policy:
It calls decode(format = 'delimited'). The actual
response Content-Type selects CSV for text/csv or
application/csv, and TSV for
text/tab-separated-values or text/tsv. Other
media retain native decoding, including plain text. Empty delimited
input returns a data frame with zero columns; header-only input retains
its columns. Parsing uses utils::read.table(), preserves
column names, respects quoted separators and newlines, disables
comments, and rejects ragged rows and parser warnings such as
unterminated quotes. Parser errors propagate. Native JSON errors retain
safe HTTP/media diagnostics.
Type inference follows read.table(). Select known
identifier or date types with
decode(format = 'delimited', col_classes = c(id = 'character'))
in a shared client policy. Without a selected policy, CSV/TSV remain
text strings.
Decoded-result transformations belong in existing
post_response hooks. The helper emits two reusable
functions, named with that helper’s prefix:
format_results <- function(state) {
records <- api_request_records(
state$result, collection = c('payload', 'records'),
query = state$params$id, null_to_na = TRUE
)
api_request_table(records, type_convert = TRUE, as_table = tibble::as_tibble)
}api_request_records() extracts only the selected path.
It wraps a named object as one record, preserves arrays and nested
fields, converts data frames to rows, and returns list()
for NULL or empty input. Query attribution must have length one or match
the record count; it becomes each record’s query attribute.
NULL-to-NA cleanup is shallow and opt-in. Use keyed = TRUE
for a named outer record collection, then
api_request_table(records, names_to = 'query_id') to retain
those keys in a column.
A response policy can attribute rows the same way from
context$query. A single-object response becomes one row
with a query column:
attributed_table <- function(response, context, decode) {
api_request_table(api_request_records(decode(), query = context$query))
}context$query is the request’s only path value, else its
only URL query value. Paging parameters such as pageNumber
do not count, so on a paged endpoint a single remaining filter (for
example studyType) arrives as context$query
and would stamp every row with a query column. A policy for
a paged endpoint should not reuse the single-object logic above; omit
query for those rows.
api_request_table() is explicitly lossy compatibility
formatting. It unions heterogeneous fields, represents missing fields as
NA, collapses nested values with '; ', and optionally
recovers types with utils::type.convert(). Set
type_convert = FALSE to keep strings such as
'001'. It rejects attribution that would overwrite a record
field. Its default output is a base data frame, including for empty
results. Passing tibble::as_tibble selects a tibble, also
for empty results, and requires tibble in the client’s
DESCRIPTION Imports. The generated helpers have no tibble
or specmill runtime dependency.
To keep your own table shape, pass
build = function(records, type_convert, names_to). It
replaces the built-in row construction (the unioned fields, the
'; ' collapsing, the position of the query
column) and must return a data frame, so it can keep list-columns, order
columns as you like, and recover types its own way.
as_table is still applied to what it returns. It receives
the records exactly as you gave them to
api_request_table(), including empty ones that the built-in
builder skips; a record has a query attribute only if you
attributed it with api_request_records(query = ). In a
batched or paging wrapper the function can be called several times: for
each request, to check the table was not edited, and once over all
requests’ records joined with c(), so record names may mix.
Keep it a pure function of its records and make it quick. Because the
function sees all the records together, any type recovery it does (it
receives type_convert) is done once over everything, as the
built-in builder does. If requests were built with different builders,
or a builder fails on another request’s records during the check, the
tables are stacked as they are instead. An error from the final call
over all the joined records is raised, not stacked.
Reuse a shared formatting function in the existing hook executor when a whole service needs it; routine policy does not require one callback per endpoint. Hooks receive decoded results and public parameters. They cannot inspect failed responses or replace policy before decoding, and no new wrapper stage is added.
Existing helpers are never rewritten by normal generation. Review
inspect_client(root)$helpers and manually adopt the
proposed template, keeping client customizations and the recorded
baseline. Emitted companion names also follow helper renames, preventing
multi-service helper collisions. EPA settings, observer registries,
PubChem Fault handling, and image conversion remain client code. This
capability does not migrate any downstream client.
Automatic contract-change deferral
Strict validation is the default. A service may opt in to enrolling failures of named diagnostic codes during apply:
Only operation-scoped findings with a listed code are enrolled. Everything else still blocks. See Routine maintenance for the lifecycle, manual enrollment, and recovery.
Relative schema servers and the source origin
Some schemas name relative servers, such as a root server
/api/v1 and an operation-level server / for
browser links. A local schema file has no download location, so these
servers cannot be resolved and their wrappers report a server
diagnostic. Record where the schema came from under the service’s
schemas:
Relative root, path and operation servers then resolve against the
origin as a browser would (RFC 3986): /api/v1 gives
https://example.org/api/v1, and an operation’s own
/ gives https://example.org/. Each operation
keeps its own server, and absolute servers are unchanged. The schema
copy is not edited. initialize_client(origin = ) writes
this setting for every service and records it in
dev/init.R. Unlike the base_url override, the
origin never replaces a server that the schema names;
base_url still overrides every operation when given. With
an origin, a server resolver (see below) treats the resolved servers as
absolute and uses its returned URL as is.
Per-service base URLs
By default every wrapper uses the server URL recorded at generation,
and the base_url override applies to the whole client. To
give each service its own host, which you can change at call time,
select a client-owned resolver:
Define the resolver in the client’s R/ source. It
receives the key and the wrapper’s recorded server, and returns an
absolute HTTP(S) URL:
service_url <- function(key, server) {
getOption(paste0('myclient.', key), Sys.getenv(key, 'https://example.org'))
}Services resolve independently, so changing one key leaves the others
in place. A relative schema server joins the resolver’s host:
/api/chet gives https://example.org/api/chet
and replaces any path the resolver returned, and an empty server keeps
the returned URL unchanged. Absolute schema servers use the returned URL
as is. The <prefix>.request base_url
option still takes precedence; the initialization override applies only
to services without a resolver. Generation fails if the function is
missing. It also fails if the client’s request helper does not accept
server_resolver; helpers created before this setting need
the upstream template change (see inspect_client()).
Opt-in typed request errors
Select request_controls.preserve_errors: true in an
operation’s request_controls to rethrow the original transport condition
and use httr2’s HTTP error classes, status and response when the decoder
checks a failed status. The default remains false, with the existing
sanitized diagnostics. Typed errors retain their original details;
clients choosing this mode control their reporting.
Adopt the released client request helper template before selecting
this control; generation rejects a helper that lacks support. With a
complete request mapping, pass
request_controls: {value: {preserve_errors: true}}
explicitly through request.arguments. The session request option can
override the same logical control.
HTTP 401 and configuration/credential failures remain hard call-level
errors and cannot be dropped. Response policies can still handle a
received status explicitly using
decode(check_status = FALSE); this control does not move
parsing earlier or bypass policies. Batch single/multiple stop/drop and
warning policies remain independent of error preservation.
Error hints
Set request_controls.error_hint to append client text to
the sanitized messages for HTTP 5xx responses and for transport
failures. It appears only after any retries are exhausted:
The message becomes
HTTP 503 response Run mypackage_sitrep() to check service status.
4xx statuses, including 401, and typed preserve_errors
errors are unchanged. A response policy that calls
decode(check_status = FALSE) builds its own messages. With
batch on_error: drop, each per-item warning repeats the
hint. The <prefix>.request session option can set or
override error_hint. Generation rejects a client request
helper that predates this control; adopt the released template first
(see inspect_client()).
Problem details in error messages
When a failed response has the media type
application/problem+json (RFC 9457), the default message
adds the server’s title and detail and a
request id, taken from the body’s request_id member or the
X-Request-ID header:
HTTP 404 application/problem+json response: Substance not found (request id 78d59eba)
Each value must be one nonempty string; control characters become
spaces and the value is cut at 500 characters. A title
equal to the detail appears once. This is the only server
text the default message carries. Error bodies of any other media type,
and problem bodies that do not parse, keep the bare
HTTP <status> <media> response message. A
configured error_hint follows the problem text. Clients
generated before this change need the upstream template change (see
inspect_client()).
The scaffold also includes a client-owned
api_request_decode() companion:
api_request_decode(response, method = 'GET', response_policy = NULL, policy_query = NULL, preserve_errors = FALSE, error_hint = NULL)
decodes an already-received response without performing transport. Its
defaults preserve the existing native decoder behavior; true enables
typed HTTP failures. A response policy receives the same
response/context/decode interface. Existing transport facades can call
this generated companion directly rather than extracting the decoder
body or maintaining a handwritten copy. For a helper named
.ct_request, the companion is
.ct_request_decode().
Request controls and batch limits
Generated project YAML includes request defaults:
defaults:
request_controls:
timeout: 30
max_retries: 0
retry_writes: false
throttle:
capacity: 5
fill_time_s: 1The throttle is a polite starting point of 5 requests per second per
host; change it to what the service documents, or delete it. Timeout is
seconds per attempt; timeout: .inf (Inf in a
runtime option) sends no timeout, for endpoints that legitimately take
longer than the 30 s default. A request that hits its timeout says so in
the error. max_retries: 2 permits three total attempts.
These values use the same inheritance as other defaults: project, API,
group or service, then operation. After editing YAML, regenerate
wrappers to update their helper calls. Runtime
<prefix>.request options override individual YAML
fields. The client-owned helper must accept
request_controls and apply those defaults; normal
generation never overwrites it. Complete request mappings own their
helper arguments and must pass any controls explicitly. Write retries
still require retry_writes: true; use that only when replay
is safe for the API.
To preserve a service’s request-rate policy, configure native httr2 throttling:
request_controls:
throttle:
capacity: 4
fill_time_s: 1
# realm: pubchem # Optional; httr2 defaults to the request hostname.Both numbers must be positive and finite; capacity must be an
integer. The same realm shares a token bucket across calls and batch
chunks in the R process. Choose identical capacity and fill time for
operations sharing a realm. Only the throttle written in YAML applies;
clients configured before the default throttle existed have none until
one is added. Runtime <prefix>.request options can
replace the complete throttle list. Existing clients must
adopt the current official request scaffold through the
helper-provenance workflow before using this control; generation does
not overwrite client-owned helpers.
Select a client-owned retry predicate by function name in declarative YAML:
Define the predicate in the client’s R/ source. It
receives an httr2 response and returns one nonmissing logical value:
retry_server_errors <- function(response) {
status <- httr2::resp_status(response)
status == 429L || (status >= 500L && status < 600L)
}This selection excludes 408 and includes 501 and 505. A service can
select a narrower predicate. With no selection, native statuses remain
408, 429, 500, 502, 503 and 504, and retries remain disabled by default.
Runtime <prefix>.request options also accept
retry_policy as a client function name or function. YAML
accepts names only, never executable code. Invalid selections fail
before HTTP; predicates that fail or return invalid values abort safely.
Write replay still requires retry_writes, and httr2 still
handles Retry-After and backoff. Connection and JSON-decode failures are
not retried.
Generated defaults expose batch.max_items and
batch.max_bytes as null (unconfigured). A top-level array
request schema’s maxItems becomes an operation-specific
default. Set limits under service defaults or individual operations, for
example:
Shared limits apply only to applicable request bodies, so ordinary
GET requests are unaffected. The helper rejects oversized requests
before sending them. Item limits apply to top-level array bodies
supplied as unnamed lists; byte limits measure the serialized UTF-8
JSON, UTF-8 plain text, or raw binary payload. Limits embedded only in
prose need explicit review; they are not silently treated as schema
constraints. Nested-array limits remain separate work. Existing
client-owned helpers need a batch argument before using
these settings; generation verifies that compatibility. To send
oversized input in several requests instead of rejecting it, see the
next section.
For a reviewed call-time setting, max_items also accepts
an environment binding:
The generated wrapper reads the named variable once per call. Unset
variables use default; empty, nonnumeric, nonfinite,
fractional and nonpositive values fail before HTTP. Resolved values,
defaults and optional caps must fit a positive R integer. Changing the
environment between calls needs no regeneration, and the client does not
depend on specmill at runtime. Literal numeric limits keep their
existing behavior. On Windows, R’s
Sys.setenv(batch_limit = "") unsets the variable, so the
default applies; platforms that retain an empty value reject it.
Use cap to keep a reviewed service maximum separate from
a caller’s preferred size. For example, line input can preserve a legacy
setting with a larger fallback while ensuring that no chunk exceeds the
service’s 200-entry limit:
The effective limit is the smaller of the resolved setting and the cap. This binding works for array bodies and explicitly selected line encoding. Existing batching runtime options may lower that effective size, following their ordinary precedence and validation rules.
Many inputs in one call: fan_out and split
Two batch settings let one wrapper call send several
requests and return one combined result:
-
fan_out: <parameter>makes a scalar path or query parameter accept a vector. The wrapper sends one request per element. -
split: truesends a top-level array body that is longer thanmax_itemsin chunks of at mostmax_itemsitems. There is no separate chunk size. The limit the API enforces is the size the wrapper splits to. -
on_error: stop | dropdecides what a failed request does. The default isstop. -
empty: <function>names a client function. Withon_error: drop, when every request fails the wrapper returnsempty()instead oflist(), for example.ct_empty <- function() tibble::tibble()to keep a table-shaped result.
Set the per-API limit once and opt operations in. Settings inherit
like every other batch field, through project, API, group,
service and operation:
# apis/comptox.yml
defaults:
batch:
max_items: 200 # what the API accepts per request
split: true # chunk larger array bodies instead of rejecting them
on_error: drop
operations:
GET /hazard/toxval/search/by-dtxsid/{dtxsid}:
batch:
fan_out: dtxsid
ct_hazard_toxval_search(c('DTXSID7020182', 'DTXSID2021315')) # two GET requests
ct_chemical_detail_search_bulk(ids) # ceiling(length(ids) / 200) POST requestsWhat is sent. Every element of a fan-out vector is
validated against the parameter’s scalar schema before any request goes
out, so a bad element fails the whole call with no partial traffic. A
split body is validated as a whole, except for its schema
maxItems, and the helper still checks
max_items and max_bytes on each chunk. Input
that fits in one request, including a single element, is sent unchanged
as one request. Requests are sequential. Other arguments, such as
projection alongside a fanned-out dtxsid, are
the same on every request.
Hooks and policies run per request. The wrapper runs
pre_request, the request, and post_response
once per element or chunk:
-
pre_requestseesstate$paramsholding one element (fan-out) or one chunk (split). Settingskip_requestskips only that request, for example on a per-ID cache hit. -
post_responsecleans or converts each response on its own. -
post_combine, an optional extra stage, runs once on the combined result. See hooks. -
response_policyreceives the element or chunk ascontext$query, provided attribution applies to the request (see Response policy). A split chunk is always attributed. A fanned-out path parameter is attributed when it is the only path parameter. A fanned-out query parameter is attributed when the operation has no path parameters and it is the only query value sent.
Cross-input validation before iteration. An
operation can select a pure client function with
validate_inputs: check_search_inputs. It receives one list
of captured parameters after normalize_inputs, before
schema checks, hooks and fan-out/split. Its return value is ignored.
Raise a client condition to reject incompatible inputs before any
requests; warnings and errors propagate directly, outside the batch drop
policy and hook executor. This setting belongs under an individual
generated operation; the named client function must exist.
Explicit inputs with a complete request mapping may use
batch.fan_out on a scalar client input, including
type: any. This lets a reviewed client normalizer accept
legacy numeric/list inputs without relaxing the source schema or native
parameter validation. Native fan-out continues to require a scalar path
or query parameter. Use the validation callback for constraints spanning
inputs, such as allowing multiple primary values only when an optional
suffix is absent.
Private hook parameters. An individual generated
operation can declare private_params, a named mapping of
literal initial values. These values join the captured parameter list
before pre_request without adding public formals. A
pre-request hook can update them with the same partial named updates as
public parameters. Explicit request bindings can read them from
params; they are not automatically added to wire parameters
or schema validation.
operations:
POST /api/resolver/getsimilaritymap:
private_params:
chemicals: null
post_params: [query, idType, section, sort, hclust_method, format]
request:
arguments:
body: {from: [params, chemicals]}pre_params selects parameter names and order for the
initial pre_request state. It requires a pre-request hook
and belongs under operations. Other inputs remain available
to request bindings. Combine it with defer_inputs when a
transport-only input must remain lazy on a skipped call; a deferred
input remains a thunk in internal request parameters and can be forced
by a pure request projection after the hook. Selection alone does not
defer input evaluation. Only selected parameter names are applied as
pre-hook updates to request parameters. Other fields in the returned
hook state remain available to the post hook. With
post_state: hook_state, the post hook still receives the
complete state returned by the pre hook, including partial params and
extra fields. By default a NULL result remains a named NULL in that
state. Select operation-only post_result_null: remove to
reproduce a client that assigns state$result <- result
and removes the result key when NULL. This requires a post-response hook
with post_state: hook_state.
For a facade that already has an all_pages input,
operation-only request.pagination selects native offset
pagination without adding public arguments. max_pages
accepts a positive integer or a request binding, such as
{from: [params, max_pages]}. A binding is evaluated after
pre-hook updates, only when paging is selected; the pagination engine
validates its value before HTTP. It requires complete native request
bindings and the current pagination companions. The when
binding runs after the pre hook and request construction; it can force a
deferred transport input. False sends one request. True uses the
existing pagination engine with explicit nested body paths:
request:
arguments: # complete native method/path/path_params/query/body bindings
# ...
pagination:
mode: offset
when: {callback: paging_enabled}
parameter: [body, offset]
size_parameter: [body, options, limit]
page_size: {from: [hook_state, request, body, options, limit]}
start: {value: 0}
max_pages: 100
items: collect_response
completed: search_complete
advance: search_next_offset
metadata: false
error_policy: partial
warn_errors: false
warn_limits: false
stop_on_empty: falseitems(response) selects each page’s collection.
completed(response, state) and
advance(response, position, page_size) are pure client
projections of response metadata. Their errors propagate, even under
partial request recovery. A raw-response collector can defer record
parsing to result_formatter after collection.
Single-request formatting receives one response; paged formatting
receives the combined collection.
post_response_scope: combined runs the existing post hook
once after this formatting and supports
post_state: hook_state for this request-level pagination. A
skipped call bypasses request construction and final formatting;
post_on_skip still runs the post hook. Dry runs return the
prepared request before page callbacks or formatting. This mode cannot
combine with operation pagination, batch iteration,
route_guard or preserve_visibility.
post_params selects parameter names and order for the
post_response state. This selection applies after
pre-request updates and only to that hook; request bindings retain the
complete state. Unknown or duplicate selections and private names
colliding with public formals are rejected. Private parameters require a
pre-request hook; selected post parameters require a post-response hook
using post_state: parameters. Both settings belong under
operations, not defaults. Without these settings, parameter capture and
hook state remain unchanged. The default skip still returns immediately
before request/post-response work; post_on_skip retains its
existing explicit behavior.
A post-response hook on the final result. Set
post_response_scope: combined on an individual
batch.fan_out or batch.split operation to run
its existing post_response hook once after combination,
metadata selection, post_combine and any
result_formatter. The hook keeps its
post_response stage and the client executor’s usual error
wrapping. The default request scope continues to run the
hook for each response.
Set post_params_source: original to give the
post-response hook parameters captured before input normalization and
pre-request updates. The default current source retains
existing capture behavior. post_params can select names
from either source. These options require a post-response hook using
post_state: parameters; they cannot be configured in
defaults.
operations:
GET /chemical/list/search/by-name/{listName}:
batch: {fan_out: listName}
normalize_inputs: {listName: normalize_list_names}
result_formatter: tidy_list_results
post_response_scope: combined
post_params_source: originalSession caches. Operation-only cache
owns lookup, environment creation and writes around a native request
mapping. It runs after input normalization and validation, before
constructing requests or resolving transport defaults. Cache callbacks
are client-owned pure key/data projections, called directly without hook
wrapping. This policy requires an unhooked operation and cannot combine
with operation batching, pagination, request pagination or
preserve_visibility.
Whole-call mode returns an existing entry immediately and stores the
final result_formatter output, including empty values:
cache:
mode: call
enabled: {from: [params, cache]}
environment: {callback: session_environment}
name: search_cache
key: search_keyenvironment selects an existing parent environment. The
generator creates the named child environment only when caching is
enabled. key(data) receives data$params and
returns one nonempty string. A hit is determined by key existence, so a
stored NULL or empty result still prevents another request. Disabled
caches do not evaluate the environment or key projections.
Per-input mode partitions hits before choosing routes and chunks. It
requires purrr in the client’s Imports, an eager public
input and a fixed positive max_items. More than one pending
input uses named sequential chunks and purrr::map; one
pending input sends directly. Thus indexed transport errors match that
collection boundary while native credential/call-level errors stay hard.
Every chunk sees the same full cache_state$pending in pure
request binding expressions, so a final short chunk does not change the
overall route choice. It also retains cache_state$params,
the original normalized parameters.
cache:
mode: items
enabled: {from: [params, cache]}
environment: {callback: session_environment}
name: property_cache
input: cid
max_items: 100
key: property_key
entries: property_entries
combine: combine_properties
project: final_propertiesHere key(data) additionally receives one
data$input. Duplicates and order are preserved in both the
hit and pending collections. result_formatter receives
result, original normalized params and
pending; for multiple pending inputs, result
is the list of per-chunk responses, otherwise one response.
entries(data) receives the formatted fresh result and
original params and returns a named list of cache values. The generator
writes those values, allowing repeated keys to overwrite in order. It
then calls combine(data) with result, cached
values in cached, and original params. Optional
project(data) receives the combined result and
original params. An all-hit call goes straight to combine/project
without transport, fresh formatting or stores. This permits raw cache
values followed by a deferred tidy projection. Projection failures
propagate; successful stores precede the final projection. Dry-run
request objects bypass cache stores and projections. The generated
client keeps this lifecycle and needs no specmill runtime.
Response cache.
response_cache saves the decoded result of a request so
that a repeated call does not reach the service again. It is separate
from the session cache above: it needs no callbacks, stores
whole decoded results and can keep them on disk. It needs the
cache companion (companions = 'cache' at
initialization, which adds cachem and rlang to
the client’s Imports).
# specmill.yml or a service file
defaults:
response_cache:
store: memory # or disk
max_age: 3600 # seconds; without it entries are kept until cleared
operations:
POST /search:
response_cache: {store: disk} # inherits max_age: 3600
POST /lookup:
response_cache: {store: memory, max_age: null} # kept until cleared
GET /status:
response_cache: nullUnder defaults it applies to GET operations and GraphQL
queries. Any other operation is cached only when it names the setting
itself, and null opts an operation out. Each block names
its own store; a max_age it does not name is
inherited, and max_age: null removes an inherited one.
memory lasts for the R session; disk keeps
entries in the user’s cache directory for the package
(tools::R_user_dir()), where they are unencrypted response
data. Disk entries outlive an upgrade of the client, so clear the store
after a release that changes how a response is decoded.
Each request is stored under a key made from the operation, every
request input (path, query, body, headers and server) and the package’s
request and response-policy options. A paged wrapper therefore caches
page by page. The key also holds a hash of each credential in use, so
two credentials never share an entry and no credential is written to the
store. Errors and dry-run requests are never stored. Neither is a result
in which a response policy returns the raw response, in a list or as an
attribute, such as
list(response = response, result = decode()): its URL and
headers can carry a credential.
Set options(<prefix>.response_cache = FALSE) to
bypass the cache for a session. The client’s internal
<helper>_cache_clear() function, called as
<package>:::api_request_cache_clear(), empties the
memory and disk stores of that helper. Generated request and replay
tests switch the cache off themselves.
The setting cannot be combined with an explicit request
mapping, route_guard, preserve_visibility, an
operation-level batch.concurrency or a server resolver. An
operation that names it together with one of these is an error; an
operation that only inherits it is generated without caching and named
in a warning, which response_cache: null on that operation
silences. An existing implementation always has a request mapping, so it
is never cached.
A disk store is shared with worker processes and a
memory store is not; see calling a wrapper without
blocking Shiny.
Final client formatting. A generated operation may
select result_formatter for a single response or for
combined fan-out, split or paginated responses:
The client-owned format_items(data) function receives
data$result and data$params with the full
normalized public inputs. It runs once after all requests, combination,
metadata selection and any post_combine hook. For an
unbatched operation it runs once after the request and its post-response
hook. Its return value is final, including NULL, unless a
combined post-response hook is selected; specmill does not restore
attributes after it. Its warnings and errors propagate unchanged,
outside both the batch drop policy and the hook executor. Existing hooks
still use their normal wrapping semantics. Use a response policy to
collect responses without decoding when parsing must wait until every
request finishes; the formatter itself must implement the desired final
projection.
This selection belongs under an individual generated operation, never
defaults. The named function must exist in the client and cannot name a
generated wrapper. It is resolved outside generated local variables. For
paged wrappers, manual all_pages = FALSE and a prepared
dry-run request bypass final formatting, as they bypass
post_combine. No formatter is selected by default.
Stable result
order. Some services return the same records with their
fields or rows in a different order from one call to the next.
result_order gives a wrapper’s table a reviewed order.
Without it a wrapper returns the order the service sent.
operations:
POST /bioactivity/search:
batch: {split: true, max_items: 200}
result_formatter: as_table
result_order:
rows: [dtxsid, aeid]
columns: [dtxsid, aeid]rows sorts the rows by the named columns, first to last,
ascending, with missing values last. Rows equal on every key keep the
order in which they were received, so name keys that identify a record.
Character keys sort in C-locale byte order (uppercase before lowercase),
factors by level, and dates and times by value. columns
puts the named columns first, in that order; the remaining columns
follow in name order, also C-locale. Give either field or both. No key
or column order is taken from the schema.
The order is applied once, to the value the wrapper returns: after
the requests are combined and after post_combine,
result_formatter and a combined post-response hook. A
single page from all_pages = FALSE and a result that a
pre-request hook supplies when it skips the request are ordered too.
Inputs and the order in which requests are sent do not change, so
sequential and parallel batches return the same table. Every row is
kept, duplicates included, and the table keeps its class and its other
attributes, such as failed.
Only a data frame with rows is ordered. A dry-run request,
NULL, a table without rows and a list of records are
returned as they are; build a table in a response policy or
result_formatter when records need an order. A table that
lacks a named column, has a list column as a row key or repeats a column
name is an error naming the wrapper. Nothing is guessed. A data.table is
an error too: it keeps its own sort key, so convert it to a data frame
or tibble first.
The setting belongs under an individual generated operation. It
cannot be combined with preserve_visibility or the session
cache. The ordering is written into the generated wrapper,
so the request helper does not change.
What is returned. The per-request results are
combined, whatever the number of inputs, so f('A') and
f(c('A', 'B')) return the same type:
- If every result is a data frame, they are combined. Tables built by
api_request_table(), in a policy or apost_responsehook, are rebuilt once from all requests’ records, so column types are recovered over the whole result and match an unbatched call over the same records. (Without this, one request’s"F"values becameFALSEand stacking them with another request’s"MF"produced"FALSE".) This applies when no hook edited the table, every request used the sameapi_request_table()options and record names agree; otherwise the tables are stacked withrbind()as they are, and a column missing from some results is filled withNA. Tables from a policy that does not useapi_request_table()are always stacked. - Otherwise the result is one list of records. A single-object response adds one record; an array response adds each of its elements, in request order.
- Requests that return nothing, such as an empty array or a hook
returning
NULL, add nothing. They are not failures.
Note that a fan-out wrapper given one ID returns
list(record), not record.
Failures. With on_error: stop, the
first failed request raises its error, and nothing is returned. With
on_error: drop, each failure gives a warning naming its
input, and the call continues:
Warning message:
Request for DTXSID2021315 failed: HTTP 404 application/json response
The combined result then carries attr(result, 'failed'),
a named character vector mapping each failed input to its error message.
For a split, the name is the chunk’s items joined with ,,
because a chunk fails as a whole. The attribute is absent when every
request succeeds. Use it to detect or retry failures in code:
x <- ct_hazard_toxval_search(ids)
failed <- attr(x, 'failed')
if (length(failed)) retry <- ct_hazard_toxval_search(names(failed))drop covers per-item failures only: the HTTP or decode
outcome of each request. An error that applies to the whole call, such
as a missing credential, an invalid runtime option, a rejected
credential (HTTP 401), or a server that cannot be resolved, stops the
call with one error, whatever on_error is, and no request
is sent. The generated code marks these errors with the condition class
specmill_call_error; errors raised inside your own server
resolver, hooks, or response policies remain per-item. A client
scaffolded before this behavior keeps its old
api_request_each() until you adopt the new helper code (see
vignette('existing-clients')).
Runtime override. The generated
on_error is a default. The helper’s batching option
overrides it for every fan-out and split wrapper of that helper, for
example to fail fast while debugging:
<prefix> means the lowercase value of
DRY_RUN_ENV with the trailing _DRY_RUN
removed, not necessarily the package name. For example,
COMPTOXR_NATIVE_DRY_RUN gives comptoxr_native.
<helper> is the request helper name without its
leading dot: .ct_request gives ct_request.
Only stop and drop are accepted here. The
companion’s keep mode does not apply, because combining
would discard its placeholders.
The option’s max_items lowers the chunk size of split
wrappers, for example to find a size a slow endpoint handles. The
configured batch.max_items stays the cap, because each
request still rejects bodies above it; a larger value stops before any
request. To raise the cap, edit the YAML and regenerate. Fan-out
wrappers always send one item per request and ignore it.
The batching companion’s api_request_batched() reads the
same option and rejects max_items, empty and
concurrency. Unset them before calling it.
Parallel batches. An operation can select bounded HTTP concurrency:
operations:
GET /items/{id}:
batch:
fan_out: id
concurrency: 4
request_controls:
max_retries: 0
throttle: {capacity: 20, fill_time_s: 1}concurrency is a positive integer, the reviewed ceiling
for wrappers with fan_out or split. Without
it, or with concurrency: 1, execution stays sequential.
Parallel execution requires httr2 >= 1.3.0 in the generated client, a
throttle, and max_retries: 0; generation stops when an
operation with a ceiling above 1 lacks the throttle or enables retries.
Newly configured clients start with a throttle of 5 requests per second
under defaults.request_controls.
The ceiling may also sit under defaults, for a service
or the whole project:
An inherited ceiling applies to every fan-out or split operation it
fits. An operation with pagination, a cache, a route guard, visibility
preservation or retries stays sequential and is named in a generation
warning. Set concurrency: 1 on an operation to keep it
sequential without the warning. A ceiling named on the operation itself
must fit, and is an error otherwise.
A session can lower the ceiling but never raise it.
concurrency = 1 sends every batch sequentially. The option
covers every wrapper in the client, so a value above a wrapper’s own
ceiling leaves that wrapper at its ceiling. To raise a ceiling, edit the
YAML and regenerate.
Setting a positive max_retries in the
<prefix>.request session option (for example
options(comptoxr_native.request = list(max_retries = 2)))
runs batches with a concurrency ceiling sequentially so eligible
requests can retry. This also applies to single-item calls. The helper
reports the switch once per session. Existing clients should adopt the
current request helper to get this behavior.
New clients declare httr2 (>= 1.3.0) in Imports;
existing clients must update that declaration before distributing
parallel wrappers. The runtime checks this version before sending
parallel requests. The parallel httr2 executor does not honor
per-request retry counts. Timeouts still apply to each request. Requests
are submitted in groups no larger than the concurrency limit, and each
group finishes before the next starts.
All pre-request hooks and request preparation run in input order before sending. Each prepared request retains its own state. Responses are decoded and post-response hooks run in input order after all HTTP requests finish; final combination, combined hooks and formatting follow as usual. Duplicates retain their input positions. Dry runs send nothing and bypass response hooks.
Every request must target the same service origin. Complete
request.arguments mappings are supported when the client
helper implements the preparation and completion contract below.
Bindings run for each chunk after pre-request hooks; include the desired
media type, headers, authentication, server selection, request controls
and response policy in the mapping. To enable concurrency, declare a
literal throttle in
request.arguments.request_controls.value. Without it, an
inherited ceiling stays sequential and generation names the operation in
a warning. An explicit ceiling above 1 is a generation error. The
executor supplies .prepare; mapping that argument
explicitly is rejected. Pagination, caches, route guards and visibility
preservation cannot combine with concurrency in this
version. This setting does not make calls return immediately or
parallelize unrelated wrapper calls. For that, a single-request
operation can set async: true; with the session option
options(<prefix>.request = list(async = TRUE)) its
wrapper returns a promise. Fixed request contracts and hook cases for
such an operation list .async = TRUE among the helper
arguments. See vignette('non-blocking').
on_error: drop retains the existing failure metadata.
With stop, or a fatal HTTP 401, errors are reported during
ordered completion after the HTTP batch has finished. Other requests may
already have succeeded, including writes; no cancellation or rollback is
promised. Call-level preparation failures stop before any requests are
sent. Interrupting execution raises an error if responses are
incomplete, rather than returning a partial success.
Existing clients must deliberately adopt the updated request helper,
including <helper>_then(), the request helper’s
.prepare argument, and the executor’s
concurrency argument and session option. Generation
diagnoses missing capabilities and preserves client-owned files. Compare
with the current template using inspect_client().
Configuration rules. Inherited settings apply only
where they fit. An API-level split: true affects only
operations with an array body and a max_items limit, and a
group-level fan_out affects only operations with that
parameter. Set on an individual operation, a setting that does not fit
stops generation:
| Setting on an operation | Requirement |
|---|---|
fan_out |
Names a path or query parameter with a scalar (string, integer, number, boolean) schema |
split |
max_items is set, on a top-level JSON array or
line-delimited text body |
on_error |
fan_out or split also applies |
empty |
fan_out or split also applies,
on_error is drop, and the function exists in
the client helper file |
fan_out with split
|
Not allowed on the same operation |
Helper adoption. Fan-out and split wrappers call two
functions in the client-owned request helper file:
<helper>_each(), which runs the requests and records
failures, and <helper>_combine(), which joins
results. New clients get both. An existing helper file that lacks them
stops generation with a message naming them; compare the helper with the
current template (see Existing
clients) and copy the two functions in. Operations without
fan_out or split generate exactly as
before.
For a new package, initialize_client() writes editable
YAML grouped by schema tags. To preview that configuration first, or
propose it for an existing package:
proposal <- specmill::configure_client(
root, schema, package = 'petstoretrial', naming = 'tag_prefix'
)
proposal$files[['apis/pet.yml']]
proposal$diagnostics
proposal$changesThe default naming = 'operation_id' preserves valid
schema names; tag_prefix turns getPetById into
pet_get_by_id. Exact tag tokens and their simple plural are
removed before adding the prefix; synonyms are not guessed. Missing IDs
use method/path names. Every proposed name is explicit in the YAML for
editing. Multiple tags use the first, with a diagnostic; missing tags
use default. group_by = 'none' creates a
single default service instead.
naming = 'path' derives names from the route instead:
segments are joined, {param} and api segments
are dropped, and a leading segment equal to the service id is stripped.
naming_options tunes it, and every result is still written
to the YAML names: map for review:
specmill::configure_client(
root, schema, naming = 'path',
naming_options = list(
prefix = list(ctx = 'ct', chemi = 'chemi'), # by API id, then family
collision_suffix = list(POST = 'bulk')
)
)With GET /api/rdkit and POST /api/rdkit
this proposes chemi_rdkit and
chemi_rdkit_bulk. GET /reports and
GET /reports/{id} share a method, so the second becomes
reports_by_id (by_param = FALSE turns that
off). prefix is a named list because a catalogue mixes
families that need different heads. Every rename is reported as
name_collision_resolved; names the rule cannot separate
remain name_collision and block generation until
edited.
Use name_case independently of that naming strategy. Its
choices are asis (the default), snake_case,
camel_case, pascal_case,
screaming_snake_case, and dot_case. Thus
naming = 'tag_prefix' with
name_case = 'camel_case' proposes petGetById.
Names already reviewed in the service YAML are kept exactly, so an
existing package can retain its convention.
When generated names collide, proposal$diagnostics lists
every contributing METHOD /path; multi-API diagnostics
include the API-qualified proposed name. Edit the matching
names entries in the existing service YAML, then rerun
configure_client(). Matching reviewed names are reused
across reruns and schema ordering, while unrelated service settings and
deliberate operation overrides remain untouched. Noninteractive runs
return these diagnostics and never prompt or silently rename a public
function.
Reviewed names are read only from the service files the proposal
would write. Pass the API catalogue as schema to reuse
names from apis/<api>.yml. A single schema path
proposes apis/default.yml or tag-named files instead, so
names reviewed elsewhere are not carried forward. A proposal gives each
route one name. When several groups wrap the same route under different
names, it keeps the first group’s name and warns. Its regenerated groups
drop the other wrappers, so keep the reviewed file and copy over only
the new entries.
mode = 'apply' writes absent configuration files only.
If existing YAML or the schema copy differs, nothing is written: review
the before/after text and make the desired edits yourself. Filename
collisions block writing; function-name collisions must be resolved in
service YAML before wrapper generation. A later proposal carries forward
matching reviewed names but never overwrites the YAML. Unsupported
operations remain included, with diagnostics. Configuration generation
does not create custom transports or hide unsupported endpoints.
load_project() and maintenance commands use
specmill.yml by default. Pass config
explicitly to use a different project filename.
Generated YAML exposes the method filter, path exclusions, schema discovery, public names, shared defaults, documentation switch and per-operation overrides. Comments explain each section and show optional authentication, formatting, callbacks, hooks and contract-test settings without enabling them unnecessarily.
Exclude methods without editing endpoint lists
In each generated service file (apis/pet.yml,
apis/store.yml, and apis/user.yml for
Petstore), replace the selection.methods list with:
selection:
methods: [GET, POST]
exclude: []
include: # Keep the existing entries below this key.
# ... existing METHOD /path entries ...This excerpt shows where to edit; keep the actual generated
include list. Selection filters intersect: an included
endpoint still has to match the allowed methods and avoid the excluded
path patterns. Leave PUT/DELETE/PATCH entries in include,
names, and operations; they do not override
the method filter. Excluded operations stay visible in the inventory but
are skipped before parsing and wrapper generation. You do not need to
review or delete hundreds of entries.
Regenerate wrappers and documentation, then reload the package:
plan <- specmill::generate_client(root, config = 'specmill.yml', mode = 'plan')
plan$operations
specmill::generate_client(root, config = 'specmill.yml', mode = 'apply')
specmill::generate_client(root, config = 'specmill.yml', mode = 'check')
devtools::load_all(root)For the bundled Petstore schema, this retains 14 GET/POST wrappers
and removes five previously generated PUT/DELETE wrappers, their exports
and help pages, including when wrappers share files. Manually modified
or unowned files remain protected; resolve any reported conflicts before
proceeding. Restore the methods and regenerate to bring the wrappers
back. Existing YAML is never overwritten automatically: older projects
can preview configure_client() and copy the desired
settings from its proposal.
| Field | Meaning |
|---|---|
config_version |
Required integer 1
|
services |
Required nonempty sequence of distinct service YAML paths |
package |
R package name; read from DESCRIPTION when omitted |
formatter |
Optional {name: air, version: '0.9.0'}; the exact
installed version is required |
callback_files |
Optional sequence of development callback source paths to fingerprint, without sourcing them |
authentication |
Map from schema security-scheme names to credential environment-variable names; never put tokens here |
Use specmill::load_project(root) to validate and inspect
the resolved service configuration before generating. Callback names
require an explicit environment even for a read-only plan.
Service files
Multiple APIs: one file per API, with nested groups
When schema is a reviewed configure_apis()
data frame, initialization writes one apis/<api>.yml
per included API. Schema tags become nested groups, not
additional YAML files. For example, 27 schemas with 69 tag groups
produce 27 API files containing those 69 groups. A single-schema
initialization still offers the original flat tag files, and existing
flat service files remain supported.
# apis/chemicals.yml
api: chemicals
schemas:
files: [schema/chemicals.json]
patterns: []
exclude: []
selection:
methods: [GET, POST]
exclude: ['^/admin(?:/|$)']
helper: chemicals_request
authentication: {}
documentation: true
defaults:
batch: {max_items: null, max_bytes: null}
groups:
chemicals_search:
selection:
methods: [GET, POST]
exclude: []
include: ['GET /search']
names:
GET /search: chemicals_search
defaults:
file: R/chemicals_search.R
operations: {}List this API file in specmill.yml under
services. Each group key is its stable service ID and must
be unique across the project. Keep those IDs when moving existing
configuration so ownership and operation identities remain stable.
Selection runs through project, API, then group.
Allowed methods intersect; path exclusions accumulate. A group cannot
restore an endpoint prohibited by its API or project. An API exclusion
affects only its own groups. The preview names the policy level
responsible for an exclusion. Group include lists and
public names remain intact even when a higher-level rule excludes an
operation.
Edit API selection.exclude once for shared route policy;
use group selection.exclude only for additional
restrictions. schemas.exclude instead filters schema
filenames. Neither setting edits the original schema document.
API schema sources, helper, authentication references, and
documentation settings are inherited unless a group overrides them.
Operation defaults merge in order: project, API, group, then operation.
Set function names and output file in groups or operations;
API defaults reject them to avoid accidental shared output names. Use
group_by = 'none' when tags are not useful: each API still
has one file with a single group. YAML file count, tag grouping, and
generated R-file layout are separate choices.
configure_client() proposals do not overwrite existing
configuration. Existing flat YAML continues to work; consolidate
reviewed settings explicitly instead of replacing them with a fresh
scaffold and losing names, exclusions, or overrides.
Project-wide limits and inherited settings
Set package-wide selection in specmill.yml, for
example:
selection:
methods: [GET, POST]
exclude: ['^/admin(?:/|$)']
helper: api_request
documentation: true
defaults:
implementation: generatedEvery service must satisfy both project and service selection rules.
Service methods intersect project methods; path exclusions accumulate. A
service cannot re-enable a project-prohibited endpoint. Exact
include lists stay in service YAML, along with names and
individual operations overrides.
Services inherit helper, documentation, and
defaults. Service values take precedence; defaults merge
recursively before individual operation overrides. Generated service
YAML leaves helper and documentation overrides commented so changing the
project setting actually affects all services. Existing explicit service
values continue to take precedence. Project defaults reject
name and file: set names and file layout per
service to avoid accidental collisions.
Print the preview to see separate lists with reasons:
plan <- specmill::generate_client(root, config = 'specmill.yml', mode = 'plan')
print(plan)
plan$excludedThe preview identifies project versus service restrictions and
matching regexes, then lists files to remove. Excluded endpoints keep
their YAML mappings so they can be restored later. The complete
plan$inventory also includes operations outside each
service’s include list; the printed summary omits those duplicates.
The default transport supports scalar path/query/header parameters,
OpenAPI string query arrays with style: form (repeated keys
when explode: true, comma-separated values otherwise), JSON
bodies, and application/octet-stream bodies declared as
type: string, format: binary, plus URL-encoded
and multipart form bodies. Pass a character vector for query arrays and
a raw vector for binary uploads. JSON is selected when offered alongside
other supported alternatives.
Initialization proposes authentication configuration for schemas declaring security schemes. Map each scheme to an environment variable for its token:
Here api_key must be the security-scheme name in the
schema; CATALOGUE_API_KEY is the environment variable
chosen by the package maintainer. Keep real tokens out of this file.
Generation writes R/api_auth.R with documented helpers:
# In the generated package, after loading it:
set_api_token('YOUR_TOKEN', scheme = 'api_key') # this session
set_api_token('YOUR_TOKEN', scheme = 'api_key', persist = TRUE) # also savePersistence updates the user .Renviron (or
R_ENVIRON_USER), preserves unrelated lines, and makes the
token available immediately. Credentials are plain text in that file. A
project .Renviron can take precedence at the next R
startup. Neither loading the package nor generating it writes
credentials. api_token() retrieves the configured value and
fails with setup instructions when it is missing.
Requests inherit top-level security unless overridden by
the operation. security: [] is public; {}
within the alternatives permits anonymous access. Generation warns when
a schema file declares security on some operations but
leaves it off others, since the gap is read as public and is often a
schema omission. Public/anonymous requests receive no automatic
credentials. Otherwise, generation supports API keys in headers, query
parameters, or cookies and HTTP bearer tokens. Each alternative is an OR
choice; all schemes inside one choice are required. Missing credentials
fail before any HTTP request. OAuth authorization-code login is
generated for a reviewed credential (see below); other OAuth flows and
OpenID Connect are not, and an unsupported-only requirement produces a
clear runtime error.
OAuth sign-in (authorization code with PKCE)
For an oauth2 scheme with an
authorizationCode flow, give the project credential an
oauth entry instead of an environment variable:
authentication:
sfn_search_api_auth:
oauth:
client_id: SCIFINDER_CLIENT_ID # environment variable, never the value
redirect_uri: http://localhost:1410/ # registered loopback URI with a port
scopes: [openid] # requested in addition to required scopes
discovery: scifinder_endpoints # optional client-owned functionThe client is public: PKCE (S256) protects the code and no client
secret is used. Generation adds api_login() and
api_logout() to R/api_auth.R.
api_login() opens the provider’s page in a browser and
receives the code on the loopback redirect_uri, so it needs
an interactive session and the httpuv package (add it to the client’s
Suggests). It requests every scope the credential’s operations require,
plus scopes. Requests never open a browser: an operation
that needs the credential fails with advice to call
api_login().
The token is kept for the session and in a per-user cache file (mode
0600) under tools::R_user_dir(<package>, 'cache'),
never in the package or project. Windows has no POSIX file modes, so
there the cache file relies on the user profile’s permissions. It is
refreshed with its refresh token shortly before it expires. When the
provider refuses the refresh, the cached token is removed and a new
sign-in is required; a network error leaves it in place. The token is
sent only to the origins of the servers the credential’s operations
call; api_login(origin = ) allows one more, such as an
institutional proxy. A token that lacks a required scope or is not
allowed for the request’s origin gives way to the operation’s next
security alternative, and fails before the request when there is none.
api_logout() deletes the cached token (it does not revoke
it).
The authorization and token URLs come from the scheme. When a
provider must be found at run time, name a client-owned
discovery function. It is called as
fn(credential, endpoints, base_url) with the schema’s
endpoints and the API origin, and returns a list with any of
auth_url, token_url and
auth_params (extra authorization parameters such as an
OpenID nonce). For example, a provider found from the
Location header of a metadata route:
scifinder_endpoints <- function(credential, endpoints, base_url) {
request <- httr2::request(paste0(base_url, '/api/oauth2/metadata'))
request <- httr2::req_options(request, followlocation = FALSE)
sso <- httr2::resp_header(httr2::req_perform(request), 'location')
list(
auth_url = paste0(sso, '/as/authorization.oauth2'),
token_url = paste0(sso, '/as/token.oauth2')
)
}Replayed tests never see the token: a recording lists the OAuth
credentials that were signed in, and replay gives those a dummy token
without reading the cache. Before recording, a token that would expire
within ten minutes is refreshed, so no token request is recorded;
recordings drop the Authorization header and are scanned
for the token values before they are kept.
For a verified endpoint whose schema omits or misstates its security requirement, record an explicit correction under that operation:
operations:
GET /bioactivity/analyticalqc/search/by-dtxsid/{dtxsid}:
security_correction:
requirements:
- api_key: []
reason: Reviewed endpoint requires the declared API-key credential.requirements replaces the operation’s effective security
using the OpenAPI array-of-requirement-maps shape described above.
Scheme names must already exist in the schema. A nonempty review reason
is required; the correction cannot be inherited through defaults. An
empty requirements sequence explicitly makes the operation public. Plans
retain the correction and the original source operation; the archived
schema is unchanged. Other operations keep their declared security.
Credential environment-variable mappings and client-owned helper
adoption still apply.
Omitting authentication preserves existing client-owned
authentication. Explicit custom request mappings also retain
responsibility for authentication. Adding the field opts into generated
authentication.
Existing helpers need optional headers,
query_serialization, body_media,
auth, parameter_serialization,
cookies, body_encoding, or
form_schema arguments when an operation uses these
features. Generation validates helper compatibility and does not
overwrite client-owned helpers.
Adapt inconsistent authentication metadata
Some APIs declare the same query key both as a required parameter and
as a security scheme, then omit that scheme’s requirement on some
routes. Combine existing settings to adapt the generated client while
keeping the downloaded schema unchanged. Verify the endpoint’s actual
contract before applying a correction; a parameter named
key alone does not establish authentication.
First, map the declared scheme directly to the environment variable
users already set. For example, in specmill.yml:
aqs_api_auth must be a declared query API-key scheme
whose wire name is key. The generated helper reads
AQS_KEY on each call. Users do not need to copy its value
into a second variable with set_api_token(). R normally
loads .Renviron at startup; restart R after editing it, or
explicitly call readRenviron('/chosen/path/.Renviron'). The
client looks up the process environment; it does not discover or read
.env files on load.
Next, under the exact operation key in service YAML, remove the duplicate wrapper argument and correct the missing security requirement:
operations:
GET /reviewed-data-route:
exclude_parameters: [key]
security_correction:
requirements:
- aqs_api_auth: []
reason: Reviewed endpoint requires the declared query API key.Replace the illustrative path with the original schema path. On
routes already declaring the correct requirement, only
exclude_parameters: [key] is needed. Both settings are per
operation. Inspect public and registration routes individually; do not
apply the correction to every operation in a service. Exclusions match
names across query, header, and cookie parameters, so check for
same-name parameters in other locations. Keep independent inputs such as
email as ordinary arguments unless their contract requires
a separate adaptation.
Read an argument from an environment variable. An
ordinary argument the user supplies on every call, such as AQS’s
email, can default to an environment variable instead:
The wrapper keeps the argument, with the default
base::Sys.getenv("AQS_EMAIL", unset = ""), so an explicit
value still wins. The value is read on each call and never written into
generated code, docs or manifests. If the schema requires the argument
and neither a value nor the variable is set, the call stops before HTTP;
an optional one is omitted. env replaces
default, exclude and required,
and applies only to scalar string path, query, header or cookie
parameters that are not paged or batched. Cassette scenarios treat these
variables like credentials, so their values never reach a recording.
Replay sends a placeholder value in its place, so a parameter whose
schema constrains the value (a pattern, enum or length) cannot use
env with cassette scenarios; generation stops and says so.
It is not authentication: nothing else reads the variable.
Plan, review, apply, and check generation. Excluding key
removes it from the public wrapper signature, so update callers,
examples, and fixed contracts. Existing client-owned helpers must
support generated authentication; regeneration does not replace them.
See update
an existing client. With fake credentials, verify exactly one
serialized key, preserved business inputs, changed environment values on
the next call, and failure before HTTP when the required credential is
unset or blank. Use a localhost server to verify wire encoding and
confirm a second generation makes no changes.
This combination was checked against an archived EPA AQS schema with 76 data wrappers and corrections on 12 routes. Offline wrapper checks, localhost requests, generation consistency, and the generated package check passed. It does not establish live EPA behavior or validate unrelated schema declarations.
Environment-backed authentication does not redact query values. Prepared dry-run requests contain the credential; httr2 request printing and verbose HTTP output can expose it. Raw errors, hooks, recordings, and server logs need their own handling. Use fake values for request inspection and never save real credentials in YAML, fixtures, or documentation.
Dry run and verbose messages
New clients export package-prefixed session controls. For
catalogueclient:
catalogueclient::catalogueclient_dry_run(TRUE)
request <- catalogueclient::get_item(item_id = 'item-1')
catalogueclient::catalogueclient_dry_run(FALSE)
catalogueclient::catalogueclient_run_verbose(TRUE)
# Subsequent requests report their HTTP method and response status.
catalogueclient::catalogueclient_run_verbose(FALSE)Both controls default to off and accept one nonmissing logical value.
Function names preserve the exact package name, including case and dots.
The option prefix is lowercase with punctuation replaced by
_. All helpers in a multi-API client share the controls.
They change session options, not profile files.
Dry-run helpers return a prepared httr2_request without
sending it. Input validation and authentication still run, so private
endpoints need credentials. The returned request may contain
credentials. Verbose messages omit URLs, headers, query values, and
bodies.
An explicit catalogueclient.dry_run option, including
FALSE, overrides the legacy
CATALOGUECLIENT_DRY_RUN environment flag. Remove the option
with options(catalogueclient.dry_run = NULL) to restore
that fallback. The flag accepts true, 1, or
yes, ignoring case. Other values leave dry run off.
These controls live in client-owned R/api_options.R and
the request helper. Existing clients need manual
adoption; regeneration does not install the setters or refresh the
helper.
Form bodies and file uploads
Generated form operations take a named body list. Omit
optional fields by leaving their names out; required fields are checked
before sending. Explicit NULL fields and empty arrays are
rejected. An empty string is a present field; an empty URL-encoded form
sends zero bytes with its form content type. Use unnamed vectors or
lists for arrays and named lists for object fields. Empty multipart
bodies are rejected; omit an optional body argument instead.
An object declaring additionalProperties: true accepts
additional finite scalar strings, numbers and booleans in URL-encoded or
multipart forms. Unknown fields use the normal scalar encoding,
including lowercase booleans and escaped names and values. Declared
property schemas still validate their fields. Closed forms still reject
additional fields. Free-form NULL, missing, binary and container values
have no selected representation and fail before HTTP; declare their
schemas and encoding explicitly when supported.
# application/x-www-form-urlencoded
create_item(body = list(name = 'Milo', tags = list('red', 'blue')))
# multipart/form-data: a file plus a JSON object part
upload_item(body = list(
file = curl::form_file('photo.png', name = 'photo.png'),
metadata = list(title = 'Milo')
))Binary parts accept raw vectors or curl::form_file()
values. Arrays of parts use repeated field names. Multipart objects use
JSON; primitive parts use text, and binary parts use
application/octet-stream, unless the schema supplies a
supported encoding.contentType. URL-encoded fields use the
schema’s encoding.style and encoding.explode
rules. Swagger 2 formData parameters and their
collectionFormat are also supported. Unsupported nested
URL-encoded shapes, dynamic form maps, and custom part headers produce
diagnostics.
To choose an offered media type, set a service default or an operation override:
defaults:
body_media: application/x-www-form-urlencoded
operations:
POST /uploads:
body_media: multipart/form-dataThe selected media type must exist in that operation’s schema.
Existing client-owned helpers need the optional body_media,
body_encoding, and form_schema arguments and
must implement their encoding; generation will not replace them. New
clients use the bundled transport and declare curl in
Imports. Adding the default transport to an existing package requires
declaring curl first; retaining a client-owned helper adds
no such requirement.
Plain-text request bodies
OpenAPI requestBody.content and Swagger
consumes may declare text/plain with a scalar
string schema. The generated wrapper validates that schema and sends
UTF-8 text with Content-Type: text/plain. Scalar strings
preserve embedded and trailing newlines, blank lines and duplicates. An
empty string sends an explicitly empty body; omitting an optional
argument omits the body. Missing values and explicit NULL fail
validation.
Select body_media: text/plain when the schema offers
several media types. Array, object, binary and composed text schemas
remain unsupported. Archived schemas are never rewritten to guess a
request contract.
If a verified endpoint accepts plain text but its archived schema declares a JSON string, record the correction under that operation:
operations:
POST /chemical/search/equal/:
body: {name: query}
body_media_correction:
from: application/json
to: text/plain
reason: Reviewed endpoint accepts newline-delimited UTF-8 identifiers.
text_encoding: lines
batch:
max_items: 200
split: truebody_media_correction supports
application/json to text/plain for a scalar
string source schema. It requires a nonempty review reason and cannot be
inherited through defaults. For the text correction, the source media
must exist and the target must be absent; conflicting
body_media selections fail review. Plans retain the
correction and the original source operation; the schema file stays
unchanged. Ordinary body_media continues to select only
declared media types.
For a Swagger 2 body with no declared request media, a verified JSON contract can be recorded with an explicit null source:
operations:
POST /api/amos/dtxsids/:
body_media_correction:
from: null
to: application/json
reason: Reviewed staging declaration and production JSON request capture.The from key must be present. This form applies only to
a declared Swagger body with no available media declaration, including
inherited consumes. Existing or conflicting declarations,
conflicting body_media selections, absent bodies and
OpenAPI bodies are rejected. The source body schema is validated
unchanged. This is a reviewed declaration for that operation, never a
JSON fallback for other AMOS routes. The same
correction/source-operation provenance is retained.
An explicitly empty responses: {} map also needs a
reviewed declaration before whole-client schema validation can accept
that operation:
operations:
POST /api/amos/dtxsids/:
response_correction:
status: '200'
media_type: application/json
description: Substance information for the supplied DTXSIDs.
reason: Reviewed staging response declaration and captured production 200 JSON.This operation-only policy requires a quoted HTTP status, JSON media, description and review reason. It cannot replace existing response declarations or conflict with declared Swagger response media. It records only the status and media; no payload fields or types are inferred from one captured response.
The archived file and source_operation stay unchanged.
The source validation report retains its original status, hash and
findings. Its reviewed entry for the service separately
records validation of the corrected in-memory document, its hash and
applied response corrections. That view passes through the same schema
validator. Other invalid operations or document defects remain blocked;
this policy never disables schema validation. Parser metadata also
retains response_correction alongside the effective
response declaration.
For a reviewed vector-of-lines input, select encoding explicitly:
operations:
POST /write:
body_media: text/plain
text_encoding: lines
batch:
max_items: 100
max_bytes: 1048576text_encoding: scalar is the default. lines
joins a character vector with LF and adds no final newline. Empty
entries, duplicates and newlines within each entry remain unchanged; an
empty vector sends an empty body. Item limits count input entries before
joining. Scalar text has no inferred record boundaries. String schema
constraints apply to the encoded text, and byte limits count its UTF-8
bytes. To split line entries, set batch.split: true with
batch.max_items. Entries are split before joining, and each
chunk is encoded and checked against the string schema and byte limit
separately. Empty entries, duplicates and embedded newlines still count
as single input entries. Without split, oversized inputs
are rejected. Scalar text has no inferred splitting boundaries. Existing
client helpers need manual adoption of plain-text transport; generation
preserves their code and provenance baseline.
For line bodies, callback and hook params retain the
original character entries for the current chunk. Encoding and
wire-schema validation use a separate value; a two-entry vector and a
single entry containing LF may produce identical bytes but remain
distinguishable to a client response callback. Request bindings that
reference the body input use its encoded wire value. Callback
expressions can still read the logical entries through
params without splitting the wire text.
Parameter serialization
OpenAPI 3.0, 3.1 and 3.2 support the following flat parameter shapes. Arrays contain strings, integers, numbers, or booleans; objects contain scalar properties or scalar-valued maps. Use unnamed vectors/lists for arrays and named lists for objects. Nested arrays/objects and unconstrained array items have no supported parameter encoding; JSON body support is broader.
| Location | Style | Shapes | Explode |
|---|---|---|---|
| Query |
form (default) |
Scalar, array, flat object | Both; default true |
| Query |
spaceDelimited, pipeDelimited
|
Array | Both; default false |
| Query | deepObject |
Flat object | Explicit true required |
| Path |
simple (default), label,
matrix
|
Scalar, array, flat object | Both; default false |
| Header | simple |
Scalar, array, flat object | Both; default false |
| Cookie | form |
Scalar, array, flat object | Both; default true |
Swagger 2 supports primitive arrays with
collectionFormat: csv (default), ssv,
tsv, or pipes in query, path, and header
parameters; multi is query-only. Ordinary cookies and
object parameters are not Swagger 2 types. Parameter
content and allowReserved: true remain
explicitly diagnosed rather than guessed. Binary parameters require
source-contract review, especially files declared in query strings
(#16).
Some generators publish an upload variant as extra query parameters
on a JSON operation; Springdoc, for example, adds files[]
(binary) and request (object) beside an
application/json body. After review, drop them for that
operation only, keeping the schema snapshot verbatim:
Quote names containing brackets; unquoted
[files[], request] is not valid YAML. Only query, header,
and cookie parameters can be excluded, and each name must exist on the
operation. The setting is per operation, not a default; other operations
keep their diagnostics, and real uploads declared as a multipart request
body are unaffected. The operation’s inventory record lists
excluded_parameters. The direct reader accepts
read_operations(file, policy = list(exclude_parameters_overrides = list('POST /api/hazard' = c('files[]', 'request')))).
Reviewed bodyless GET/HEAD subset
An optional request body can be omitted by a reviewed operation policy:
operations:
GET /api/resolver/ghs-list-count:
request_body_correction:
omit: true
reason: Reviewed bodyless production GET returns the existing count records.This policy generates no public body argument and sends no request-body bytes. It selects only the bodyless subset of a declared optional OpenAPI GET/HEAD body; it does not claim that the service ignores supplied bodies. The schema’s original operation and the correction remain in plan metadata, and the archived schema is unchanged. Other operations keep their request bodies and diagnostics.
A reason is required. Omission is rejected for required or absent
bodies, Swagger 2, other HTTP methods, and operations with a body-media
override or correction. It belongs under operations, never
service or project defaults. Review live bodyless requests before
applying it; this setting does not repair or infer a body’s media type
or payload contract. ### Reviewed path declarations
When a published schema has missing or incorrectly named path parameters, an operation-only correction can replace its effective path declarations after review against service-owned documentation and captured requests:
operations:
GET /api/amos/get_similar_structures/{identifier_type}/{identifier}:
path_parameters_correction:
parameters:
identifier_type: {type: string}
identifier: {type: string}
reason: Reviewed staging declarations and production read-only captures.parameters maps wire names to parameter schemas. Every
replacement is required; the normal parser validates its schema and
requires exact agreement with the route placeholders. Query, header and
cookie declarations keep their existing behavior. The correction
replaces all path declarations for this operation, including any
inherited from its path item. Other operations keep their original
declarations. It does not rename public inputs; use
parameters and parameter_order for that.
Plans retain path_parameters_correction,
source_operation and the original schema hash. The archived
schema is never rewritten. Supply only constraints established by the
reviewed contract; an empty successful response does not prove an
accepted identifier or record-type vocabulary.
Hook-selected routes
When a pre-request hook chooses another schema route, declare it on the keyed operation:
Each reference is schema-file METHOD /path. Use a unique
basename or a path relative to the project root. The file must be loaded
by the same service; ambiguous basenames and unknown routes fail
configuration loading. Targets need not be selected for wrapper
generation. routes belongs under operations, not defaults,
and duplicate declarations are rejected.
The keyed route and every target must use the same effective helper,
resolved schema server URL, and selected request body media, including
absence of a body. Unresolved servers fail this comparison. Binding
server from hook_state does not relax the
schema-server check; runtime server overrides remain client-owned. This
declaration does not verify the hook’s parameters or runtime route
choices.
For operations with declarations, the inventory’s optional
routes field lists the keyed route followed by its targets,
with project-relative schema paths, schema hashes, operation keys,
helpers, servers, and body media. Generated-file provenance records the
same list under .specmill/manifest.json →
files → output filename → routes → operation
ID. A hook-bound endpoint or method without
declarations emits a configuration warning. Runtime guarding is opt-in.
For standard generated helper calls, set route_guard: true
on the operation. For complete request mappings, name the helper
arguments that carry the method and schema path explicitly:
operations:
GET /api/descriptors:
routes:
- 'chemi-rdkit-prod.json GET /api/rdkit'
route_guard: {method: method, path: endpoint}The guard evaluates the final mapped arguments once after pre-request
hooks and rejects a method/path pair absent from the reviewed routes
before calling the helper. It accepts the keyed route and declared
targets, using exact uppercase methods and schema paths, including any
unexpanded path placeholders. Both values must be single nonmissing
strings. Full URLs are not schema paths. Complete mappings must supply
both named arguments; names are never inferred. The guard requires
declared routes and a generated implementation. Set
route_guard: false or omit it to preserve existing
behavior. Skipped requests bypass the guard, including
post_on_skip handling.
Runtime server overrides are independent of method/path review and remain available. This guard does not validate the destination server, redirects, parameters, or changes made inside a custom helper. Generated guards use base R and do not require specmill at runtime.
For APIs that explicitly require repeated bracketed query-array names, opt in:
brackets sends a flat primitive array as
expand[]=customer&expand[]=invoice (with URI percent
encoding). It applies to query arrays in the selected service or
operation, regardless of their declared array style. schema
restores the normal schema-driven behavior for an operation. This is an
explicit convention, not an interpretation of OpenAPI
deepObject for arrays: the OpenAPI
definition defines deepObject for objects, while Stripe’s expansion
examples show repeated expand[] keys.
Only arrays of strings, integers, numbers, or booleans are covered.
Object, path, header, cookie, JSON, and form-body encodings keep their
existing behavior. Nested arrays, object items, unions, binary items,
null elements, and empty arrays remain unsupported. No API is detected
automatically and no schema is rewritten. The direct reader accepts the
same opt-in as
read_operations(file, policy = list(query_array_style = 'brackets')).
Existing helpers must implement the bracket style in their existing
parameter_serialization handling; accepting the argument
alone is insufficient.
For example, a query object list(R = 1L, G = 2L) becomes
R=1&G=2 with exploded form, p=R,1,G,2 with
non-exploded form, or p[R]=1&p[G]=2 with deepObject.
Exploded cookies become separate name=value pairs joined by
;. URI tokens are UTF-8 percent-encoded before delimiters
are added; literal percent escapes are data and are encoded again.
Header values are not URI-encoded. New boolean array/object encodings
use true and false; existing scalar helper
behavior is retained.
Omitting an optional argument uses its schema default, if any;
explicit NULL omits it. Empty scalar strings remain
provided values (p= in query/cookies, ;p in
matrix paths, . in label paths). Empty containers are
rejected because URI templates do not give them an unambiguous
representation distinct from omission. Null elements, missing/non-finite
scalars, duplicate object names, and nested values are rejected before
HTTP. Non-exploded whitespace-delimited values cannot themselves contain
the whitespace delimiter; composite header values cannot contain their
structural delimiter. These cases fail instead of silently changing the
values received by the server.
Existing scalar and form-style string-query-array wrappers retain
their helper arguments, including query_serialization.
Newly supported encodings pass parameter_serialization
metadata (location, name, schema, style, explode, required status, and
Swagger collection format); cookies additionally pass a
cookies list. Before generating these operations into an
existing client, review its helper against the current
inst/templates/request.R implementation and add these
optional arguments and their serialization behavior,
retaining the client’s base URL, authentication, hooks, and response
handling. Merely accepting ... does not implement the
encoding. Generation never replaces a client-owned helper, and a helper
without the required arguments fails planning with an explicit migration
message. Complete custom request mappings continue to own their
serialization.
The matrix follows the OpenAPI parameter specification and RFC 6570, including comma-separated non-exploded labels. Offline tests verify the received URI, headers, and cookies through the generated client rather than relying on helper return values.
JSON body values
Generated wrappers accept named lists for objects and unnamed lists
for arrays, including single-item arrays. Where the schema type is
exactly array, an unnamed atomic vector is also accepted
and sent as a JSON array, so c('a') sends
["a"] and character() sends [].
Union types and oneOf/anyOf/allOf
schemas, including values nested inside them, still reject vectors
because a length-one vector could be a scalar; pass a list there. For a
declared object, list() becomes {}; for a
declared array it stays []. In unconstrained values, use
setNames(list(), character()) for {} and
list() for []. Scalars are single strings,
finite numbers, or logical values. Heterogeneous arrays can contain
these scalars, nested lists, and NULL. Other atomic
vectors, data frames, classed objects, missing values, and duplicate or
empty object names are rejected; convert them to plain JSON-shaped lists
explicitly.
Omit an optional body argument to send no body. Explicit
body = NULL sends JSON null when allowed by
the schema: unconstrained values, a nullable OpenAPI 3.0 type, or an
OpenAPI 3.1 null type (including a type array); otherwise
it fails. Inside an object, list(field = NULL) retains the
field as null, while leaving the name out omits it.
Required fields must be present, even when their values may be null.
Wrappers pass an explicitly unboxed JSON null to the existing helper for
a top-level null; no new helper arguments are needed. Client-owned
helpers still control their own serialization.
Open objects accept extra fields. A schema in
additionalProperties validates each extra value;
additionalProperties: false rejects extra fields. Fixtures
and wrappers share these checks. Examples may supply fixture values but
never establish a type. Swagger 2 body arrays may omit
items; OpenAPI 3.0 arrays and Swagger 2 non-body arrays
must supply it. Explicit items: {} accepts any JSON value.
Boolean schemas remain diagnosed; this is not a full JSON Schema
validator.
JSON bodies support finite recursion when a plain local
$ref points back to an ancestor schema from an optional
object property. Default fixtures omit that recursive child. Supplied
children retain the ancestor’s required fields, types, and constraints.
Required back-edges, recursion through array items or typed maps, and
recursive references with siblings remain outside this slice and produce
diagnostics. This restriction also applies to nullable required cycles.
Parameters and form bodies retain their existing recursion
diagnostics.
Body values are limited to 32 levels below the root and 20,000 nodes, including unconstrained fields. Validation also stops after 20,000 schema visits. Environments are rejected as non-JSON values; cyclic lists terminate at the depth limit with a possible-cycle error. Values beyond these limits fail before transport, without dropping or truncating content.
JSON request bodies support oneOf, anyOf,
and allOf at the body root, in properties, in array items,
and in typed maps. Pass ordinary R values:
# For oneOf branches requiring either values or records:
body <- list(values = list('first', 'second'))
# The other branch might accept:
body <- list(records = list(list(id = 1L), list(id = 'second')))oneOf requires exactly one matching branch;
anyOf requires one or more; allOf requires
every branch. Sibling constraints also apply. Supplying fields that
satisfy two open-object branches of oneOf is an error, even
if a discriminator names one branch. Discriminators are hints, not
validation shortcuts, and wrappers neither insert tags nor strip fields.
These rules follow JSON
Schema composition.
Within composed values, container shape is explicit: use
setNames(list(), character()) for {} and
list() for []. Branch matching never changes
one into the other. Closed allOf members each check the
whole object; declaring a field in another member does not override
additionalProperties: false. OpenAPI 3.1
type: [string, 'null'] accepts strings and explicit null;
nullable alone has no validation meaning in 3.1.
Fixtures try a finite set of candidates from declared examples,
defaults, enums, and branch shapes, then validate against the complete
schema. They do not infer types from examples or solve arbitrary
intersections. If no candidate passes, supply a reviewed fixture
override; an ambiguous oneOf value still fails.
Branch matching checks types, required fields, typed maps, closed objects, enum/const values, numeric and string bounds, patterns, array length/uniqueness, and object size. Unsupported assertion keywords in JSON bodies produce an operation-specific diagnostic; malformed supported constraints are schema defects. Formats remain annotations. Form-body compositions remain diagnosed because their wire representation needs separate support; response schemas remain metadata, without generated response validation.
Path, query, header, and cookie parameters also accept
oneOf, anyOf, allOf, and OpenAPI
3.1 type arrays. specmill encodes the value by the branches’ shared wire
shape and validates it against the complete schema, so each branch keeps
its constraints:
- A nullable parameter, such as
anyOf: [{type: integer}, {type: 'null'}], encodes like its non-null branch. Parameters have no encoding for JSON null:NULLomits an optional parameter, and a required one must be supplied. - A union of scalar types accepts a value of any branch type.
- A union of a scalar and an array encodes as an array; a single value sends one item.
- A union of objects encodes the fields of the matching branch.
-
allOfmerges its branches, which must share a type.
Unions that mix object and non-object branches, allOf
branches without a shared type, and schemas that only admit null remain
parameter_composition diagnostics. A default that fails the
complete schema is reported by the default check below. A client-owned
request helper predating this support encodes scalar unions only in
simple query, path, and header positions; adopt the current helper for
label, matrix, or cookie scalar unions and for arrays of mixed scalar
types. Complete request mappings and explicitly retained implementations
remain the customization paths for unsupported contracts.
For nullable parameters, omission uses a declared default if present;
explicit R NULL omits an optional parameter. Required
arguments must be supplied with a non-null scalar. There is no inferred
URL encoding for JSON null: neither an empty query value nor the literal
string "null" represents null automatically. Sending a
service-specific null encoding requires an explicit client mapping or
helper.
Local references are resolved relative to the containing file; remote
references are never fetched, but can resolve from reviewed local copies. Cycles and
reference chains exceeding 100 levels are diagnosed. OpenAPI 3.1 local
schema-reference siblings are conjunctive. For a bundled reference with
assertion siblings, use an explicit allOf containing the
reference and the sibling constraints; a diagnostic prevents lossy
merging.
id: catalogue
schemas:
files: [schema/catalogue.json]
helper: api_request
selection:
methods: [GET, POST]
exclude: ['^/internal/']
documentation: true
policy_version: reviewed-1| Field | Meaning |
|---|---|
id |
Required stable service identity, unique in the project |
schemas.files |
Sequence of literal local JSON, YAML, or YML paths |
schemas.patterns |
Sequence of root-relative file globs; each must match files |
schemas.exclude |
Sequence of case-sensitive regexes matched against schema basenames |
helper |
Required client runtime function name, defined in
R/
|
selection.methods |
Uppercase methods to include; omitted means all standard HTTP methods |
selection.include |
Exact METHOD /path allowlist; omitted means all
operations, empty selects none, unknown keys fail |
selection.exclude |
Case-sensitive stringr regexes; exclude an original path if any
matches. Prefix an entry with a method
(POST ^/api/thing/?$) to exclude only that method at
matching paths |
selection.unclaimed |
Service level, without include: true
selects only operations that no other service on the same declared
server claims through include or operations;
the plan reports the claiming service. Claims are by
METHOD /path key, so a sibling’s key counts even if its own
methods or exclusions drop it. Method prefixes are uppercase |
names |
Map from METHOD /path to public wrapper name |
documentation |
Boolean; true generates roxygen, help pages, and
exports; initialization sets it to true |
policy_version |
Your review/version label, recorded in generation metadata |
defaults |
Operation settings shared across the service |
operations |
Settings keyed by METHOD /original/path
|
hooks |
Map from public wrapper name to ordered pre/post hook sequences |
hook_config |
Existing runtime hook YAML path; use this or hooks,
never both |
hook_callback |
Client hook executor name; default run_hook
|
prepare |
Development callback name; receives and returns an operation, preserving identity |
contracts |
Inline fixed request expectations; see Testing |
contracts_file |
Fixed call sequences under tests/testthat/: RDS
(preserves R classes) or readable YAML/JSON keyed by wrapper name or
METHOD /path
|
response_fixture |
Default mock response for inline single-call contracts |
files and patterns can be combined; paths
are deduplicated and sorted. Missing files, unmatched globs, or an empty
final schema selection fail. Unknown fields, duplicate explicit keys,
invalid types/regexes, executable YAML tags, and name collisions are
errors. YAML aliases are supported; explicit keys override merged keys.
YAML contains data, never R source strings.
Name and document a wrapper
Generation checks the effective default of each optional API parameter after configuration overrides and preparation callbacks. A default must pass the same supported schema-value checks as a supplied argument. Native request defaults must also pass parameter encoding checks. Empty query strings, empty containers, header newlines, and ambiguous serialization delimiters can therefore fail independently of schema constraints.
mode = 'plan' reports
parameter_default_schema or
parameter_default_transport, the operation and parameter,
the value and its origin, the source location, and guidance. Both codes
use review_required: an incompatible default annotation
does not establish that an OpenAPI 3.1 schema is invalid. Apply and
check stop before writing output when a selected operation has an
invalid effective default. Specmill does not coerce or silently discard
such defaults.
Correct a default in service configuration without changing the input schema:
operations:
GET /chem/tanimoto:
parameters:
query nBits: {default: 2048}
query radius: {default: 2}
GET /depict/2D_enhanced:
parameters:
query arrow: {default: null}An explicit null override emits R NULL, which omits an
optional parameter. Defaults on required arguments are ignored because
no R default is emitted; excluded parameters and defaults on body
schemas are also outside this check. Client-only inputs, custom
renderers, and explicitly retained implementations keep their existing
validation contracts. Complete request mappings retain schema-value and
wrapper checks but own their transport encoding.
Add this to the service that selects the catalogue schema:
operations:
GET /items/{item_id}:
name: fetch_item
parameters:
path item_id: {name: identifier, description: Catalogue item ID.}
query language: {default: en}
docs:
title: Fetch one catalogue item
description: Retrieve one item in the requested language.
parameters:
identifier: The catalogue identifier, for example item-1.
language: Response language; en or fr.
return: An R list containing the decoded item response.
examples:
- {identifier: item-1}
- {identifier: item-1, language: fr}
tags:
family: catalogue endpointsParameter overrides use original location plus name,
such as path item_id. Documentation and example inputs use
the resulting public R names, such as
identifier. Examples are input maps rendered as calls
inside dontrun, so a documentation build does not send
their requests.
Rename the body argument. A request body is an
argument named body (or body.1 when a
parameter already has that name) unless the operation says otherwise.
body takes a name and a
description, like a parameter override:
operations:
POST /hazard/toxval/search/by-dtxsid/:
body: {name: dtxsid, description: DSSTox substance identifiers.}The wrapper becomes f(dtxsid), still sends that value as
the body, and documentation, examples and batch.split
chunking use the new name. The description replaces the
generated @param text; the note about chunking long arrays
is still appended. Without a body setting the output is
unchanged. Generation stops, naming the operation, when the name
collides with another argument, is not a valid R argument name (or one
the generated code uses internally, such as params), when
the operation has no request body, or when body is combined
with a complete inputs map. It belongs under
operations, not defaults. Request mappings and
hooks that read the body (from: [params, body],
state$params$body) must use the new name, and renaming a
wrapper that is already generated shows up as a signature change in
mode = 'plan'.
docs supports title,
description, parameters, return,
examples, tags, and lifecycle.
docs.parameters can also document the body argument under
its public name (body, body.1, or the
body.name override); that text takes precedence over
body.description. Without overrides, titles/parameter text
come from schema metadata and the return text describes the helper
response. Improve these for your users: document units, valid IDs,
result classes, and service-specific errors.
lifecycle accepts experimental,
stable, maturing, superseded,
deprecated, defunct, questioning,
or soft-deprecated. Install lifecycle in the
documentation environment when using badges. Lifecycle is explicit
policy; upstream deprecation is not automatic permission to change a
wrapper’s lifecycle. Protected lifecycle badges can prevent later
regeneration.
tags supports metadata such as family,
keywords, seealso, aliases, and
client custom tags with existing roxygen handlers. Maintain custom
handlers in your client package. Executable and structural built-in tags
are rejected. Schema descriptions are treated as prose, not executable
configuration.
Group endpoint families
Initialization groups operations by tag and writes the resulting
choices as editable YAML. Function prefixes are opt-in through
naming = 'tag_prefix'; the package still has one R
namespace. For example, a Petstore service can contain:
id: pet
schemas: {files: [schema/openapi.json]}
selection: {include: ['GET /pet/{petId}']}
helper: api_request
documentation: true
names:
GET /pet/{petId}: pet_get
defaults:
file: R/pet.R
docs:
tags: {family: pet endpoints}
operations:
GET /pet/{petId}:
parameters:
path petId: {name: pet_id}This exposes pet_get(pet_id) while preserving
/pet/{petId} on the wire. List separate
apis/pet.yml, apis/store.yml, and
apis/user.yml files in the project’s services
sequence to maintain independent policies for each group. Their combined
selections can cover the entire schema. The full
Petstore example demonstrates native generation, explicit mappings,
and retained client code; petstore_example(path) builds it
from the files shipped with specmill.
Operation settings
| Field | Meaning |
|---|---|
name |
Override public R function name; must agree with names
if both specify it |
helper |
Override the service helper for this operation |
file |
Output path directly under R/, for example
R/catalogue.R
|
implementation |
generated (default) or existing, which
retains a declared implementation |
parameters |
Schema parameter overrides: name, default,
required, exclude,
description
|
body |
Request-body argument override: name,
description
|
extra_parameters |
Additional public inputs: default,
required, type, description, plus
schema constraints minimum, maximum,
items (validated) and format (annotation
only) |
inputs |
Complete public input map, replacing schema-derived inputs; same
fields plus missing_as_null
|
parameter_order |
Sequence of public names, including the request-body argument, to place first; remaining parameters follow |
request.arguments |
Named helper arguments built from typed bindings |
post_on_skip |
Boolean, default false; run post-hook after a pre-hook skips the request |
post_state |
parameters (default) or hook_state for the
full pre-hook state |
docs |
The documentation policy described above |
Use the body’s public name in parameter_order. For
example, body: {name: dtxcid} with
parameter_order: [dtxcid] places the body before optional
query parameters. Without a body rename, use body, or its
collision-adjusted name such as body.1 when a schema
parameter already uses body. Omitting
parameter_order preserves the default order with the body
last.
Per-operation settings merge into defaults. Named maps merge
recursively; sequences, a complete inputs map, individual
request bindings, and default values replace their
corresponding defaults. Keep defaults small enough that you can see the
effective behavior of each operation.
A complete inputs map needs
request.arguments. Required inputs have no R default and
preserve ordinary R argument semantics, including explicitly supplied
NULL; the existing helper/hooks own value validation.
missing_as_null: true is available only for explicitly
required inputs when an existing hook must see omission as
NULL. Do not use it merely to silence missing-input
errors.
Map public inputs to your existing helper
The default helper contract is:
api_request(method, path, path_params, query, body)To preserve a different helper interface, explicitly replace its argument map:
operations:
GET /items/{item_id}:
name: fetch_item
inputs:
identifier: {required: true, type: character}
verbose: {default: false, type: logical}
request:
arguments:
endpoint: {value: items}
identifier: {from: [params, identifier]}
options:
compact_object:
verbose: {from: [params, verbose]}Here the helper must accept endpoint,
identifier, and options. Extra inputs are sent
only when explicitly bound. Each binding has exactly one form:
| Binding | Result |
|---|---|
{value: items} |
Literal R data |
{from: [params, identifier]} |
Read a public input |
{from: [hook_state, query]} |
Read pre-hook state; requires a pre-hook |
object: {key: <binding>} |
Named R list, retaining NULL entries |
compact_object: {key: <binding>} |
Named list omitting NULL entries; empty result is
list()
|
array: [<binding>] |
Unnamed list, preserving positions including NULL |
vector: {key: <binding>} |
Named c() values |
{callback: batch_limit} |
Development callback result: literal data or an R language object |
For JSON, use named lists for objects and unnamed lists for arrays,
including one-element arrays. NULL, false,
zero, and one-element lists are distinct. Do not turn arrays into scalar
values for convenience. The helper owns final serialization and
transport checks. Schema-derived public parameters and bodies are
validated before request mapping and runtime hooks. Complete client
inputs maps retain their documented client-owned
validation.
Parameter transports use optional NULL for omission and
reject required NULL; they do not encode JSON null. Empty
parameter containers have no unambiguous wire representation. Form
fields likewise reject null and empty arrays. JSON bodies retain their
declared nullability and container constraints. Ordinary scalar
query/path/header booleans retain R’s
TRUE/FALSE spelling; structured parameter
serialization, JSON, and forms use
true/false.
Development callbacks versus runtime hooks
For a complete example, see Configure and maintain runtime hooks, including optional executor scaffolding, installed-client behavior, and regeneration.
A development binding callback receives one operation while generating source:
callbacks <- new.env(parent = baseenv())
callbacks$batch_limit <- function(operation) {
quote(as.numeric(Sys.getenv('batch_limit', '1000')))
}
specmill::generate_client(
root, config = 'specmill.yml', callbacks = callbacks, mode = 'plan'
)Use {callback: batch_limit} as a request argument
binding. A language object such as quote(...) becomes
client runtime code; a string remains a quoted literal. A
prepare callback instead transforms an operation record and
must preserve its identity. These functions run during planning too:
keep them deterministic and free of filesystem/network side effects.
Runtime hooks execute when a user calls the generated wrapper:
Hooks are client-owned request-shaping code. They may intentionally
change a validated public value’s type, remove values, or build a
different request body and options under their returned state. Existing
hook_state mappings select which state reaches the helper.
Hook authors own these transformations and any validation they require;
specmill adds no mandatory post-hook schema gate or outgoing-contract
declaration. Generic helpers retain their transport checks. Hook
exceptions propagate without calling a fallback request.
Schema-derived public inputs, including empty-query restrictions, are
checked before pre_request. An empty query created by a
hook is therefore the hook author’s responsibility. Explicit client
inputs preserve their existing missing/NULL behavior
described above.
hook_callback: run_hook
hooks:
fetch_item:
pre_request: [validate_identifier]
post_response: [tidy_item]The wrapper invokes the client’s executor as
run_hook('fetch_item', 'pre_request', list(params = params)).
The executor runs the named chain in order and returns state. Returned
public parameters replace only those provided by the pre-hook. State can
contain skip_request and result. By default, a
skipped request returns immediately. Post-hook input normally contains
result and params, and the post-hook returns
the final wrapper result.
Set post_on_skip: true to run post-processing on a
skipped result, or post_state: hook_state to pass the
complete pre-hook state with its result replaced. Both require a
pre-hook. Hook functions/executor must exist in client runtime source.
Unused runtime declarations appear separately in
unused_hooks.
Validate the result
After any configuration change, run load_project(), then
generate_client(..., mode = 'plan'). Inspect
files, drift, diagnostics,
mapping_diagnostics, and retained_diagnostics.
A client-mapped operation uses your explicit serializer
mapping and keeps its original parser limitations visible; it does not
acquire native schema support.
Apply only reviewed changes, then run check and the client’s tests.
Pagination
Select companions = c('batching', 'pagination') in
initialize_client() to emit reusable helper-prefixed
functions into the existing client-owned request helper. They use the
same ownership baseline and manual-adoption rules as transport. Wrappers
make a single request unless you opt in: batch.fan_out or
batch.split loop over a wrapper’s own input (see Many inputs in one
call), and pagination fetches every page (Fetch every page in one call).
Emission requires no specmill runtime dependency. Pagination adds digest
to a new client’s Imports; an existing DESCRIPTION must declare it
first. A third companion, cache, is described under response cache.
Use a shared policy list in retained client code, or the
package/helper-scoped options
<prefix>.<helper>.batching,
<prefix>.<helper>.pagination, and
<prefix>.<helper>.pagination_links. The option
prefix is derived from DRY_RUN_ENV, as defined above. For
example catalogueclient.api_request.pagination applies to
that helper only. A leading dot in the helper name is dropped, so helper
.ct_request reads
comptoxr_native.ct_request.batching. Multi-API helper
prefixes keep service policies separate. Explicit pagination arguments
override policy fields; a supplied batching policy replaces the shared
list. Nothing is inferred from parameter or response names. Maintainers
supply API knowledge once per service, with operation exceptions; the
companions supply the loops.
Fetch every page in one call
The pagination setting makes a generated wrapper request
page after page and return the pages combined. It is explicit: an
operation without the setting stays a single request. Set it once for a
service and it applies wherever its parameter exists; operations can
override single fields or opt out:
# apis/catalogue.yml
defaults:
pagination:
mode: page # numeric page iteration; cursor mode is described below
parameter: pageNumber # original name of an integer or number path or query parameter
start: 1 # becomes the default of that parameter in the wrapper
completed: empty # empty (the default) or the name of a client function
max_pages: 100 # the default of the wrapper's max_pages argument
operations:
GET /items/{kind}:
pagination: {max_pages: 20} # override one field
GET /reports:
pagination: null # opt out of the inherited settingWhere it applies. An inherited setting reaches only
operations that have the named parameter, as a path or query parameter
with an integer or number schema. The others stay single requests. A
setting written on an operation itself must fit that operation, or
generation stops and names it. mode and
parameter must both be present once the levels are merged.
On an operation with batch.fan_out or
batch.split, each item or chunk pages to completion with
its own max_pages, and the results are then combined;
all_pages = FALSE sends one request per item.
on_error: drop applies per item, so a failure on a later
page drops that item and its earlier pages. pagination
needs a generated implementation. Cursor mode accepts a string path,
query or explicit client parameter and reviewed
next_cursor, items and completed
callbacks. See the cursor example in
vignette('paged-wrappers') for GET queries and complete
POST body bindings. Offset paging, item caps and page-size arguments
still use the companion functions in retained code, described below.
The starting page. start becomes the
wrapper’s default for the page parameter. It is required when the
parameter is optional and has no default. It cannot be set when the
parameter is required or already has a default configured under
parameters. At call time the caller’s value is the page the
loop starts from.
When paging stops. With
completed: empty the loop stops at the first empty page. A
response with no body, or an empty list or table, is an empty page. An
API that marks its last page some other way takes a client function,
which receives the page’s result and a state list
(position, requests, item_count,
page_size) and returns one TRUE or
FALSE:
last_page <- function(response, state) any(response$last)The function must exist in the client’s R/ files;
generation checks. A page limit always applies: reaching
max_pages stops the loop and warns.
Each page’s result must itself be the collection: a table, or a list
of records. A response that wraps the records in an envelope is never
empty, so the loop would run to max_pages. Many APIs do
this, for example
{"pageNumber": 1, "totalPages": 3, "data": [...]}, and keep
answering with an envelope whose data is empty past the
last page. Unwrap it in the response policy. If the envelope says which
page is last, tag the table with those fields so a completion function
can read them:
envelope_policy <- function(response, context, decode) {
body <- decode()
table <- api_request_table(
api_request_records(body, collection = 'data', query = context$query)
)
attr(table, 'paging') <- body[c('pageNumber', 'totalPages')]
table
}
last_page <- function(response, state) {
paging <- attr(response, 'paging')
paging$pageNumber >= paging$totalPages
}With completed: last_page, the loop stops on the last
page without asking for another. With completed: empty it
makes one more request to see the empty page. Attributes a policy
attaches to a page’s table stay available to completed and
post_response; the combined result does not carry them,
whether it holds one page or many, and the tables are still typed once
over all pages. A hook that only changes an attribute of a page’s table,
without touching its data, is not kept either.
What the wrapper looks like. After its other
arguments it gains all_pages = TRUE and
max_pages = <n>. Both names are fixed, and a
collision with another argument stops generation. With
all_pages = FALSE the wrapper is the plain single-request
wrapper: its hooks run once, and it returns the page as it always did,
with no pagination attribute and no
post_combine. A dry run returns the first page’s prepared
request, without post_combine. Otherwise it returns the
pages combined as a batched wrapper does, so tables built with
api_request_table() are typed once over every page, and the
result carries attr(, 'pagination'), a list of
requests, item_count and
stop_reason (empty_page,
completed or max_pages). The caller guide is
Fetch every page of a result.
To preserve a plain legacy result, set
pagination: {metadata: false} on the operation. The default
is true. This field is operation-only, so inherited paging
settings keep their existing metadata behavior. With false,
the wrapper removes the generated pagination attribute
before post_combine; it will not restore that attribute
afterward. Page completion, limit warnings, error propagation, manual
single-page calls and dry runs keep their existing behavior. The same
setting works when paging is nested inside fan-out. Other result
attributes are not removed by this policy.
Hooks and policy. pre_request, the
response policy and post_response run once per page. An
optional post_combine hook runs once on the combined result
(see hooks).
A pre_request hook must not change the page argument; the
wrapper owns it, and a hook that does stops the call with an error
before the request is sent.
Contracts. A single-call fixed contract cannot
describe a paging wrapper, so generation requires it to set
all_pages: false in its inputs. A calls
contract describes the page sequence: one entry per page request in
order, ending with the empty page (or with page max_pages),
and a result that includes the pagination
attribute unless operation policy disables it.
The client helper. The loop uses
<helper>_paginated(),
<helper>_combine() and
<helper>_pages() in the client-owned helper file.
Initialize a new client with the pagination companion. For an existing
client, compare the helper with the current template and adopt them;
generation stops with a message naming what is missing, and also when
<helper>_paginated() is an older version that needs a
page size. The runtime option
<prefix>.<helper>.pagination cannot change the
shape of these wrappers’ results, because the wrapper fixes the controls
that would. Hitting max_pages warns, as the emitted
companion’s warn_limits is TRUE.
New service files include a commented pagination line as
a reminder.
The companion functions in retained code
Batching accepts explicit normalize(items),
build(chunk, index), and merge(results)
functions. Values/order and unmerged results are preserved by default.
on_error = 'drop' or 'keep' warns on failures
and respectively drops them or retains error_result. The
size must be a positive integer before HTTP. Duplicate/missing/empty
removal, singleton JSON arrays and raw text construction remain selected
client choices. Every chunk routes through existing transport. An
explicit first_batch_only = TRUE batching policy preserves
ComptoxR’s legacy pagination of only its first batch. General
composition processes every chunk.
The convention inventory used for this implementation is:
| Convention | Inputs and response | Support |
|---|---|---|
| Page number | A zero- or one-based page, a page size, and a collection, possibly nested | Explicit starting page; increment by one |
| Offset | An offset, a limit, and a collection | Explicit starting offset; increment by requested size |
| Cursor | An opaque token in a response body and a token argument on the next request | Explicit token argument and extractor; repeated tokens rejected |
| Next link | A response body URL or an HTTP Link header |
paginated_links() with a bodyless httr2 GET request;
same origin only |
The bundled catalogue’s list_items(page) demonstrates
why parameter names are insufficient: its schema supplies neither a size
parameter nor an end condition. It is not automatically pageable.
Existing extension points include public input and request mappings,
pre-request and post-response hooks, custom request helpers, and
retained implementation: existing functions. Hooks can
normalize a response; a separate companion can orchestrate repeated
calls without changing the public single-request contract. The helper
and companion are client-owned R files.
For an operation with public arguments page,
per_page, and category:
list_all_items <- function(category, max_pages = 100, max_items = NULL) {
api_request_paginated(
list_items, category = category,
mode = 'page', parameter = 'page', size_parameter = 'per_page',
start = 1, page_size = 50, items = function(response) response$data,
max_pages = max_pages, max_items = max_items
)
}
result <- list_all_items('books')
result$stop_reason
result$pagesFor a top-level collection and offset/limit arguments:
search_all <- function(query, max_pages = 100, max_items = NULL) {
api_request_paginated(
search_items, query = query,
mode = 'offset', parameter = 'offset', size_parameter = 'limit',
start = 0, page_size = 50, items = identity,
max_pages = max_pages, max_items = max_items
)
}Use exact public argument names, including any configured renames.
Fixed arguments must be named and cannot override the pagination
arguments. If an operation’s argument collides with a
paginated() control such as items or
start, use a small adapter function that closes over that
fixed value. Use exact nested paths such as
parameter = c('body', 'pagination', 'cursor') and
size_parameter = c('body', 'pagination', 'limit') to update
request state without rebuilding filters, options or sort fields.
Companions and generated functions remain independent of specmill at
runtime.
The extractor must return a list, atomic vector, or data frame. Data
frames count rows. NULL is rejected to catch missing response fields;
explicitly convert a known null/204 end response to an empty collection
in the extractor if the API uses that convention. Extracted pages retain
their collection type and are not merged. Empty pages are omitted and
produce stop_reason = 'empty_page'. Short pages continue; a
full final page therefore requires another call to discover an empty
page. Page numbers advance by one, offsets by the fixed requested size.
For response-selected offsets, supply
advance = function(response, position, page_size) position + response$recordsCount.
Select Spring completion with
completed = function(response, state) response$last or
compare state$requests to an explicit
response$totalPages. Nested hasNext metadata belongs in the
same callback. stop_on_short = TRUE selects short-page
termination.
max_pages and an optional max_items must be
finite positive integers. Emitted companions default to 100 calls and no
item cap, and warn on truncation. The toolkit functions retain 100/10000
and silent-limit defaults for backward compatibility. The last
collection is sliced to meet the item limit without changing the request
size. Limits bound calls and retained items, not response bytes or total
time. Transport retries can make multiple HTTP attempts per call. A
limit produces max_pages or max_items, with
the item limit taking precedence when both are reached. Neither means
that all available items were fetched. Repeated nonempty pages terminate
at these limits without deduplication. Request, decode, and extraction
errors propagate immediately by default. Explicit
error_policy = 'partial' or 'empty' warns
after a failed request and returns successful pages or an empty
collection respectively. Extraction and security failures still
propagate. Keep #63 response policy output as a decoded envelope, or
retain {response, result} explicitly and extract from
result. Totals and cursor metadata must survive until iteration
finishes. A selected format(result) runs once afterward;
post-response hooks that remove metadata must be omitted or adapted for
these fetches.
Cursor responses, including AMOS
mode = 'cursor' takes the exact public cursor argument
name and a next_cursor function. The default
start = NULL is passed explicitly on the first call. Use
start = '' if the operation requires an empty string
instead. Supply a resume token explicitly when resuming.
size_parameter and page_size may both be NULL
when the companion fixes the size itself. Cursor values must be strings
or NULL; they are never decoded, modified, inferred from item IDs, or
treated as URLs.
AMOS development and staging return a results array and
a pagination object containing hasNext,
limit, and nextCursor. Configure a generated
GET wrapper for /api/amos/method_keyset_pagination/{limit}
as follows:
all_methods <- function(max_pages = 10, max_items = 500) {
api_request_paginated(
amos_page, mode = 'cursor', parameter = 'cursor',
size_parameter = 'limit', page_size = 50,
items = function(x) x$results,
next_cursor = function(x) {
if (isTRUE(x$pagination$hasNext)) x$pagination$nextCursor else NULL
},
max_pages = max_pages, max_items = max_items
)
}For the filtered POST form, put the cursor in the body through a companion:
filtered_page <- function(cursor, limit) {
amos_filtered(limit = limit, body = list(
cursor = if (is.null(cursor)) '' else cursor,
filters = list(internal_id = list(
filterType = 'text', type = 'startsWith', filter = 'GJ-'
))
))
}Pass filtered_page in place of amos_page.
Keep filters and sort order fixed throughout retrieval. The generated
functions retain their one-request behavior. NULL or an empty next token
ends with no_next_cursor. Repeated tokens, including cycles
back to the initial token, raise an error before another request. Empty
pages stop even if a token is present; limits stop before token
extraction. These stops take precedence over detecting repetition in an
unused next token.
Next links in bodies or headers
Generated wrappers return decoded bodies, so they do not expose HTTP
headers. paginated_links() instead takes an httr2 request;
its extractors receive the full httr2 response. It requires httr2 1.3.0
or later and a bodyless GET request.
request <- httr2::request('https://example.org/items?limit=50') %>%
httr2::req_timeout(20)
# HTTP Link header, rel="next", is the default next-link extractor.
result <- api_request_paginated_links(
request, items = function(response) httr2::resp_body_json(response)$data,
max_pages = 10, max_items = 500
)
# A body-provided next URL uses the same retrieval and origin checks.
result <- api_request_paginated_links(
request, items = function(response) httr2::resp_body_json(response)$data,
next_link = function(response) httr2::resp_body_json(response)$next,
max_pages = 10, max_items = 500
)Configure authentication on the original request. Each link must
match its scheme, hostname, and effective port before that request’s
credentials are used. Relative links resolve against the current
response URL. URL userinfo and fragments are rejected. All redirects are
disabled, including same-origin redirects; a redirect response is an
error. The next URL supplies its complete query string, so initial query
arguments are not automatically appended. NULL or an empty link ends
with no_next_link. Repeated resolved links are errors;
finite limits also bound cycles that change their URL spelling. Error
messages for invalid/repeated links do not include their values.
Cross-origin links, redirect traversal, link-based POSTs, and
composite/non-string cursor objects are unsupported. Use a client-owned
helper for such contracts; never edit generated wrappers. AMOS validates
cursor behavior, not next-link behavior. The localhost tests exercise
body and header links, relative resolution, cycles, and credential
isolation. The opt-in dev/verify_amos_pagination.R script
checks generated GET and filtered POST wrappers against dev or staging
without production access or credentials.
Normalize selected inputs before validation
An operation may name client-owned functions in
normalize_inputs, keyed by public input names, including
renamed parameters and body inputs:
Each function receives one input value and returns its replacement.
Functions run once per wrapper call, in mapping order, before
required/type/body checks, parameter capture, hooks, and iteration. They
resolve in the client wrapper’s enclosing environment. The generated
client does not depend on specmill at runtime. For example,
clean_identifiers may deduplicate identifiers, remove blank
or missing values, and reject an empty result with a client-specific
error. The normalized value still undergoes the usual native validation.
An early error does not force unrelated option arguments.
The setting belongs under an operation, not service defaults. Unknown public input names and invalid function names are rejected. The function must exist in the client at call time. Array-body splitting uses the normalized whole input to form chunks. No normalization is inferred for other inputs, duplicates, or text lines; line encoding preserves its existing entry boundaries and newline bytes unless that input explicitly opts into a client function.
Deferred client inputs
By default, wrappers capture every public input eagerly before request hooks. For a reviewed facade with response-only options, an operation can defer selected client inputs:
Each selected value in params becomes a zero-argument
function. Client hooks pass it through unchanged, and the response
callback calls params$tidy() when formatting needs that
option. The function evaluates the original R argument promise, so
repeated calls evaluate the supplied expression once. This lets initial
input guards and body-option capture run first, followed by request
cleanup, HTTP, and response formatting. A request or cleanup failure
need not force the response-only argument.
Only explicit inputs or extra_parameters
can be selected. Native wire parameters, unknown names, duplicate names,
and inputs also selected by normalize_inputs are rejected.
The policy belongs under operations, not project or service
defaults, and requires a generated implementation. It does not change
the public signature or automatically invoke deferred values in request
bindings: client code must call them where the reviewed contract needs
them. Other inputs and existing frontloaded normalizers keep their
behavior.
Error policy by request count
Reviewed operations that abort one failed request but retain partial results for multiple requests can select both branches explicitly:
operations:
GET /items/{id}:
batch:
fan_out: id
on_error: {single: stop, multiple: drop}
empty: empty_tableThe runner selects a branch from the number of chunks after input
normalization and effective batch sizing, including runtime limits. Two
entries sent in one array request use single; two separate
requests use multiple. Both choices must be
stop or drop. Existing literal policies and
session policy overrides keep their behavior. A client
batch.empty constructor is allowed when either branch drops
failures. Credential and other call-level errors still abort every
branch. This policy applies to errors reaching the runner; a client
response policy can separately handle received HTTP responses before
decoding.
An operation can set batch.warning: failure_warning to a
client function function(error, items) that formats each
dropped request’s warning. It receives the original error condition and
that request’s normalized chunk. Return one nonempty string for the
warning, or NULL to suppress it.
batch.warning: false suppresses dropped-request warnings
directly. Omitting the field keeps the existing warning text. This
setting requires a dropping branch and belongs under operations. Adopt
the current request helper before using it.
The formatter runs only for dropped request errors. Credential and
other specmill_call_error conditions bypass it and abort.
Formatter failures or invalid return values also abort. For exact HTTP
wording, an existing client response policy can raise a structured error
containing the reviewed status or route; the formatter can read those
fields without parsing an error message. Result metadata and the
batch.empty constructor remain separate policies.
batch.fallback_warning: true changes what
NULL from the formatter means. Instead of suppressing the
warning, the wrapper emits the default text,
Request for <items> failed: <message>, which
names every item of the dropped request. A nonempty string from the
formatter is still emitted once, unchanged. Use it when a formatter
words some failures, such as HTTP errors, and must not hide the others,
such as a timeout:
operations:
POST /bulk:
batch:
split: true
max_items: 100
on_error: {single: stop, multiple: drop}
warning: http_warning
fallback_warning: trueThe setting belongs under operations and requires a
batch.warning function; it is an error without one or with
batch.warning: false. The fallback text is written into the
generated wrapper, so the request helper does not change. Sequential and
parallel batches warn alike.
To make a wrapper that drops failures silently report them, change one thing at a time and review each as a change to what callers observe:
- Remove
batch.metadata: false, so the result’sfailedattribute names every dropped request. - If the formatter returns
NULLfor some failures, addbatch.fallback_warning: true, so those still warn. If the wrapper is silent because ofbatch.warning: false, remove that line instead: the default warnings return, and the fallback applies only to a formatter function. - Regenerate, then compare warnings and attributes for a failing call before releasing the client.
Plain batch result attributes
A reviewed operation can use batch: {metadata: false}
alongside fan_out or split to suppress the
generated failed attribute for dropped requests. The
default remains true. Suppression happens before
post_combine, and the wrapper does not restore the
suppressed attribute after the hook. Per-request warnings and call-level
errors keep their existing behavior.
Use the existing batch.empty client function to choose
the container when every request fails, for example an empty tibble
instead of a list. This constructor does not change partial-success
combination. batch.metadata belongs under
operations, never project or service defaults.
Preserve a single helper call’s return visibility
An operation may set preserve_visibility: true to
forward its helper’s visible or invisible return, including
NULL, without changing the value or attributes. The
generated wrapper ends with the helper call rather than assigning and
then returning its result. This also works with reviewed request
bindings and route guards. The default remains the existing visible
result behavior.
This policy belongs under an operation and requires an unbatched,
unpaged generated wrapper without hooks or post_on_skip.
Pipelines that combine or replace results have separate return behavior
and are rejected by this setting. The policy does not add file-upload
support or change request construction.
Chunking an explicit client input
For an operation with explicit inputs, select the input
to split separately from the schema body:
inputs:
query: {type: any, required: true}
batch:
input: query
split: true
max_items: {env: batch_limit, default: 100}batch.input belongs under one operation, requires
split: true, and must name an eager explicit client input.
Existing body-array splitting is unchanged. Each send receives the chunk
in params$query; a pure request body projection can wrap
that chunk in the schema’s object shape. Final formatters and combined
hooks receive the complete normalized input. Native
credential/configuration errors and the existing single/multiple request
error policy remain unchanged.
As with existing body-array splitting, an empty input sends one empty
chunk. Use the existing validate_inputs preflight when a
facade must reject empty input before HTTP.
Reviewed duplicate response declarations
When two loaded schemas describe the same request but disagree about its response, select the reviewed response source explicitly:
operations:
GET /api/alerts/render:
duplicate_response:
source: chemi-alerts-prod.json
reason: Reviewed PNG/SVG response declaration for the shared render routeThe source must identify one loaded duplicate. Request parameters, security, server and other operation metadata must still agree. Without this policy, conflicting duplicates remain errors. The selected response drives generation; both source response contracts and hashes are retained in inventory and file ownership provenance. File ownership records use project-relative source paths so an unchanged checkout remains fresh when moved. This does not rewrite either schema.
Declared alternative routes compare the configured server resolver, key, relative base path and recorded absolute fallback. A common resolver can join relative OpenAPI and hostless Swagger routes with the same base path; different resolver settings or fallback URLs remain errors.
Schema formats
Schemas are detected by registered importers. OpenAPI 3.0, 3.1 and
3.2, Swagger 2.0, reviewed ArcGIS REST captures, Google API Discovery
documents and saved GraphQL introspection results are currently
implemented. Other recognized descriptions report their format and the
supported importer list; recognition alone does not enable generation.
Use an API-level or flat-service format: openapi or
format: swagger to override detection. API groups inherit
that setting. Omit it to detect each source automatically.
For a catalogue, supply a format column in
configure_apis()’s choices data frame or
maintain format: in specmill-apis.yml; a blank
catalogue format means automatic detection. Format selection happens
before the review table is built. Detected source_format
and importer_version are read-only metadata, also recorded
per schema in generated ownership provenance. Importer registration is
internal until the extension contract stabilizes.
OpenAPI 3.2
An OpenAPI 3.2 document is validated against the official 3.2 schema
and read like OpenAPI 3.1: its Schema Objects follow JSON Schema
2020-12. A Media Type Object given by reference
(#/components/mediaTypes/...) is resolved. Four constructs
that only 3.2 defines are not generated:
- A
queryoperation is listed as excluded with codequery_method. - An
additionalOperationsentry is listed as excluded with codeadditional_operation. Neither needs policy, and neither blocks generation. - A parameter with
in: querystringmakes its operation unsupported (querystring_parameter). - A request body that uses
itemSchemamakes its operation unsupported (sequential_media).
Exclude an unsupported operation in selection policy to generate the
rest. Sequential request media types such as
application/jsonl are reported as unsupported body media,
as before. Tag parent, kind and
summary, $self and the other descriptive
additions are not used; operations are still grouped by tag name, and
references still resolve against the local file.
ArcGIS local captures
ArcGIS imports use reviewed local JSON captures rather than fetching
metadata at runtime. In a checkout,
source('dev/capture_arcgis.R') provides the development
capture utility. Give it public directory or FeatureServer/MapServer
URLs and a new or empty output directory. It follows metadata listings
once, records source URLs and hashes, and writes one service capture per
supported service plus a directory index. It records inaccessible
directories and unsupported service types as diagnostics. Review the
files before using them as generation inputs.
source('dev/capture_arcgis.R')
root <- '/path/to/new/client'
capture_arcgis(c(
'https://echogeo.epa.gov/arcgis/rest/services',
'https://services.arcgis.com/cJ9YHowT8TU7DUyn/arcgis/rest/services/National_Measured_Conductivity/FeatureServer'
), output = root)
apis <- specmill::configure_apis(
root, schemas = file.path(root, 'directory.json'), review = FALSE
)
# Review apis and its source_diagnostics attribute before initialization.
specmill::initialize_client(
root, apis, package = 'myarcgis', title = 'My ArcGIS client',
author = list(given = 'Your', family = 'Name', email = 'you@example.org'),
license = 'MIT'
)
specmill::generate_client(root, config = 'specmill.yml', mode = 'plan')Service captures contain arcgis_capture_version: "1",
kind: "service", a reviewed service url, its
native document, and layers entries containing
their own url and native document. Tables are
included in that layer list. Every advertised leaf layer/table must have
a local capture; missing captures fail instead of silently reducing the
API. Directory captures have kind: "directory" and
services, a list of relative service-capture paths. Use
format: arcgis-rest to override detection in API
configuration if needed.
Query parameters include where, outFields
and returnGeometry. Offset and page-size arguments are
emitted only when the layer advertises pagination. Initialization writes
explicit offset paging policy using resultOffset,
resultRecordCount, the captured record limit, and
client-owned callbacks for exceededTransferLimit. The
caller’s page-size argument sets both the requested size and offset
stride, including after renaming the argument. Empty pages do not end
traversal when the server says more records remain. Page caps still
limit requests. Paged query wrappers return feature records;
all_pages = FALSE returns one page of those records.
Nonpaging wrappers retain the response envelope and do not accept paging
controls.
MapServer captures can emit service-level identify;
relationships expose queryRelatedRecords. Some
related-record endpoints omit the transfer-limit flag even for a full
requested page. Their generated completion callback probes after a full
page when the flag is absent and preserves related groups across pages.
Explicit server flags take precedence. FeatureServer edit wrappers
require declared editing capabilities. Their form body accepts JSON text
for adds/updates and a comma-separated ID
string for deletes; values are not guessed or coerced into
geometry objects. No edit requests are made by import or generation.
Root ArcGIS error payloads raise even with HTTP 200, without copying
potentially sensitive server messages into errors. Callers must inspect
per-edit results for partial edit failures.
Token-capable server metadata does not imply that every service is
protected. Set requires_token: true in a reviewed service
capture only when that service requires it. The IR uses a
session_token query scheme and records a captured
generateToken endpoint/flow when available. Generated
clients read the token from their configured environment variable. Token
acquisition and renewal stay client-owned; imports never sign in or
persist credentials. OpenAPI-specific source corrections do not apply to
ArcGIS captures.
Google API Discovery documents
A Google API Discovery document
(kind: "discovery#restDescription") is read from a local,
reviewed file. Download the document for the API version you use, review
it, and pass it to initialize_client(). Nothing is fetched
at generation time. Use format: google-discovery to
override detection in API configuration if needed.
specmill::initialize_client(
'/path/to/new/client', 'airquality-v1.json', package = 'myairquality',
title = 'My air quality client',
author = list(given = 'Your', family = 'Name', email = 'you@example.org'),
license = 'MIT'
)Each method becomes one operation named after its method id, with the
service name removed. Path and query parameters come from the method.
The request body and response come from the named schemas the method
refers to. System parameters that apply to every method, such as
alt, fields and prettyPrint, are
not added as arguments.
Initialization writes cursor paging policy for a method that takes a
pageToken query parameter and returns
nextPageToken. The generated wrapper follows the token
through a client-owned callback; all_pages = FALSE returns
one page. When the token travels in the request body, initialization
reports body_page_token and leaves paging to reviewed
policy.
The API key is sent as the key query parameter from the
environment variable named in specmill.yml. OAuth scopes
are recorded, but sign-in and token refresh are not generated. 64-bit
integers, durations and field masks stay strings, as the API sends them.
Three cases are reported instead of generated:
- Media upload (
media_upload_unsupported): only the metadata request is available. - A path that uses reserved expansion (
{+name}) without an equivalentflatPath(reserved_expansion): the method is left out. - A page token carried in the request body
(
body_page_token): the method is generated without paging.
OpenAPI-specific source corrections do not apply to Discovery documents.
GraphQL introspection results
A GraphQL service is described by a saved introspection result: the
JSON answer to the standard introspection query, kept as a local
reviewed file. Schema language (.graphql) files are not
read yet. Introspection names no server, so pass base_url:
the endpoint URL without its last path segment. Requests go to
<base_url>/graphql; set graphql_path
under the service defaults when the last segment
differs.
specmill::initialize_client(
'/path/to/new/client', 'introspection.json', package = 'mygraph',
title = 'My GraphQL client', base_url = 'https://api.example.org/api/v4',
author = list(given = 'Your', family = 'Name', email = 'you@example.org'),
license = 'MIT'
)Each root query and mutation field becomes one operation with the key
query <field> or mutation <field>,
grouped into query and mutation services.
Field arguments become wrapper arguments and are sent as GraphQL
variables, never written into the query text. An omitted optional
argument is not sent. Argument values are not validated locally; the
service checks them. An argument’s default is copied into the query as
the introspection result prints it. If a service prints defaults in a
form that is not valid GraphQL, set query_document for that
operation.
A wrapper requests the fields listed for its operation. Initialization writes a default list: the scalar and enum fields of the return type, one level deep, leaving out deprecated fields and fields that take required arguments. Edit the list and regenerate:
A name is a scalar or enum field; a one-key map selects fields of an
object. __typename is always available. Generation reports
graphql_selection when a listed field is not in the schema,
an object field has no nested list, or a field takes required arguments,
and selection_required when a return type has no scalar
fields and nothing is listed. Those operations are not generated until
the list is reviewed or the operation is excluded. For anything a field
list cannot express, such as fragments, selections on unions and
interfaces, or arguments on nested fields, set
query_document to a complete reviewed query. Its variables
must keep the argument names.
Every request is a JSON POST. The client-owned
api_request_graphql_response callback raises
specmill_call_error whenever the response has an
errors entry, also with HTTP 200 and partial data. The
server’s messages are attached to the condition as errors
and kept out of its message, because they can echo variable values.
Otherwise the wrapper returns the value of the root field;
NULL when the service answers null.
Not generated in this version: subscriptions (reported as
subscriptions_unsupported), automatic pagination,
authentication (introspection declares none) and recorded test scenarios
for GraphQL operations. Queries are sent with POST, so automatic retries
apply only when retry_writes is enabled.