OpenAPI & ODCS Contracts
Recon builds contracts from what it already has: your .http requests and the responses in the Flight Recorder. recon export openapi writes an OpenAPI 3.1.0 document. recon contract infer writes an ODCS v3.2.0 data contract for one response. You can then check any recorded run against an OpenAPI file or an ODCS contract.
Quick start
Section titled “Quick start”Infer a contract from a recorded run and check another run against it:
recon contract infer 01a22d22-db71-7526-83bf-b9b2acfcae86 --name students -o contracts/students.odcs.yamlrecon contract check contracts/students.odcs.yaml 01a22d22-db5b-7215-bdf8-6e5de1aa2070Contract `students` check: INVALID (2 rows, 4 violation(s)) [DK_TYPE_MISMATCH] gpa: Column `gpa` expected `number`, got `string` [DK_REQUIRED_NULL] student_id: Required column `student_id` is missing or null [DK_TYPE_MISMATCH] gpa: Column `gpa` expected `number`, got `string` [DK_REQUIRED_NULL] student_id: Required column `student_id` is missing or nullExport an OpenAPI spec and check a run against it:
recon export openapi -o build/openapi.yamlrecon contract check-openapi build/openapi.yaml 01a22d22-db5b-7215-bdf8-6e5de1aa2070OpenAPI check (GET /v1/students -> 200): INVALID (4 violation(s)) [OPENAPI_REQUIRED_MISSING] $.students[0].student_id: Missing required property `student_id` [OPENAPI_TYPE_MISMATCH] $.students[0].gpa: Expected type [number], got `string` [OPENAPI_REQUIRED_MISSING] $.students[1].student_id: Missing required property `student_id` [OPENAPI_TYPE_MISMATCH] $.students[1].gpa: Expected type [number], got `string`Get run IDs from recon history.
Export OpenAPI
Section titled “Export OpenAPI”recon export openapi [-o PATH] [--title TEXT] [--version TEXT] [--no-airlock]| Flag | Default | Description |
|---|---|---|
-o, --output |
none | Also write the YAML to this file. Missing parent directories are created. |
--title |
workspace name |
Sets info.title. |
--version |
1.0.0 |
Sets info.version. |
--no-airlock |
off | Skip PII masking of response examples. Known secret values are still replaced. |
The command always prints the result, even with -o. Human output is the YAML. JSON and agent output is {"airlocked": ..., "spec": ..., "yaml": ...}.
Output for the demo workspace:
info: description: OpenAPI 3.1 specification synthesized by Recon from `.http` collections and Zero-PII Airlocked Flight Recorder samples. title: recon-demo version: 1.0.0openapi: 3.1.0paths: /v1/enrollments: post: operationId: campus_demo_stripe_prod_key_leak_check requestBody: content: application/json: example: amount: 2500 schema: properties: amount: type: integer required: - amount type: object required: true responses: '200': description: Successful response for Stripe Prod Key Leak Check summary: Stripe Prod Key Leak Check tags: - Security Drills /v1/students: get: operationId: campus_demo_list_students responses: '200': content: application/json: example: environment: local... students: - email: micah.vaughn.9383@example.edu full_name: Eli Bennett gpa: 3.92... schema: properties:... description: Observed HTTP 200 response for List Students x-recon-odcs-schema: list_students summary: List Students tags: - Campus SISservers:- description: Workspace environment `local` url: http://127.0.0.1:4401/_sandbox/local- description: Workspace environment `staging` url: http://127.0.0.1:4401/_sandbox/stagingHow the document is built
Section titled “How the document is built”Servers. Each environment’s base_url becomes a server, if it is a plain value without {{. Duplicates are dropped. If no environment qualifies, the server is http://127.0.0.1:8080 with the description “Default local server”.
Paths. Each request becomes one operation. The path comes from the request URL:
- A leading
{{base_url}}(or any leading{{var}}) is removed. A fullhttp://orhttps://URL is reduced to its path. - Segments written as
{{id}},:idor{id}become{id}path parameters. Each isrequired: truewith typestring.
Operation fields.
| Field | Source |
|---|---|
summary |
Request name. |
operationId |
Request ID, lowercased, with runs of other characters turned into _. The name is used when the ID is empty or untitled. Duplicates get _2, _3 and so on. |
tags |
The request folder, if set. |
parameters |
Path parameters, query parameters and header parameters (see below). |
security |
From the request’s auth block (see below). |
requestBody |
From the request body (see below). |
responses |
From a recorded run (see below). |
Query and header parameters. Query keys come from the URL’s inline query string (keys containing {{ are skipped) and from enabled query entries. Header parameters come from enabled headers, except Authorization, Proxy-Authorization, Cookie, Set-Cookie, Content-Type, Accept, Content-Length, Host, User-Agent, X-Api-Key and X-Auth-Token. All are optional strings. An example is added only when the key does not contain secret, token, password, key or auth, and the value is not empty and has no {{. Inline query keys never get an example.
Security schemes. These are added to components.securitySchemes when a request uses them. See Auth & Request Signing for the auth types.
| Request auth | Scheme name | Definition |
|---|---|---|
| Bearer or OAuth2 | bearerAuth |
type: http, scheme: bearer |
| Basic | basicAuth |
type: http, scheme: basic |
| API key | apiKey_{key} (key lowercased, other characters as _) |
type: apiKey with the key name, in: header or query |
| AWS SigV4 | awsSigV4 |
type: apiKey, name: Authorization, in: header |
| HMAC | hmacSignature |
type: apiKey with the signature header name, in: header |
A literal Authorization: Bearer ... header with no auth block produces no scheme.
Request bodies. Every body is marked required: true.
| Body type | Media type and schema |
|---|---|
| JSON | application/json. Known secret values are replaced first. The schema is inferred. An example is added when the body has no {{. A body that is not valid JSON gets type: object. |
| Form | application/x-www-form-urlencoded, an object with one string property per enabled field. |
| Multipart | multipart/form-data, an object with a string property per part. File parts have format: binary. |
| Text | text/plain, type: string. |
| Binary | application/octet-stream, type: string, format: binary. |
Responses. Recon loads the 80 most recent runs. For each request it uses the latest run with the same request ID. If there is none, it uses the most recent run with the same method and a matching path.
- With a run, the response is keyed by the run’s status code. Its description is “Observed HTTP
{status}response for{name}”. If the body is JSON, it gets anapplication/jsonschema and the body as anexample. - By default the body is passed through the PII Airlock before it is used, and the response gets
x-recon-odcs-schemawith the inferred contract name. - With
--no-airlock, only known secret values are replaced. Real names, emails and other PII from the response end up in the example. - Without a run, the operation gets
"200": {"description": "Successful response for {name}"}.
Schema inference
Section titled “Schema inference”Response and request schemas are inferred from a single JSON sample:
| JSON value | Schema |
|---|---|
null |
type: null. As an object property: type: [string, null], and not required. |
| boolean | type: boolean |
| whole number | type: integer |
| other number | type: number |
| string | type: string, with format date (YYYY-MM-DD), date-time (RFC 3339 or YYYY-MM-DD HH:MM:SS), uuid, or email when the value looks like one |
| array of objects | items is one object schema built from all items. A key is required only when every item has it with a non-null value. |
| other array | items is the union of the item types. integer and number merge to number. Mixed types give a type list. |
| empty array | items: {} |
| object | properties for every key, required for every non-null key |
Infer an ODCS contract
Section titled “Infer an ODCS contract”recon contract infer <RUN_ID> [--name NAME] [-o PATH]| Argument | Default | Description |
|---|---|---|
RUN_ID |
required | The run whose response body is used. |
--name |
request name | Contract name. It is lowercased and non-alphanumeric runs become _. |
-o, --output |
none | Also write the YAML to this file. |
The command always prints the YAML, even with -o. JSON and agent output is {"document": ..., "yaml": ...}.
recon contract infer 01a22d22-db71-7526-83bf-b9b2acfcae86 --name studentsapiVersion: v3.2.0kind: DataContractid: studentsname: studentsversion: 1.0.0status: activedescription: purpose: Inferred by Recon from API endpoint `http://127.0.0.1:4401/_sandbox/local/v1/students`. usage: Validate API payloads and detect breaking drift with `recon` or `datakeel`.schema:- name: students physicalName: http_127_0_0_1_4401_sandbox_local_v1_students properties: - name: email logicalType: string physicalType: text required: true unique: true... - name: gpa logicalType: number physicalType: double precision required: true unique: true... - name: student_id logicalType: string physicalType: text required: true unique: true primaryKey: true customProperties: - property: reconJsonPath value: studentsInference rules
Section titled “Inference rules”Rows. A top-level array uses its object items as rows. An object that holds a non-empty array of objects uses the first such array as rows, and its key is saved as the reconJsonPath custom property. Any other object is a single row.
Types. Each value is classified as one of these logical types, with a matching physical type:
logicalType |
physicalType |
JSON value |
|---|---|---|
string |
text |
string |
integer |
bigint |
whole number |
number |
double precision |
other number |
boolean |
boolean |
boolean |
date |
date |
10-character YYYY-MM-DD string |
timestamp |
timestamptz |
string of 19+ characters in RFC 3339 or YYYY-MM-DD HH:MM:SS |
array |
jsonb |
array |
object |
jsonb |
object |
any |
jsonb |
mixed types that do not merge |
When rows disagree, types merge: integer and number give number; date and timestamp give timestamp; date or timestamp with string give string; anything else gives any. A field that is always null is string.
Flags.
required: the field is present and non-null in every row.unique: required, at least two rows, and every value differs.primaryKey: the first unique field namedidor ending in_id.maxNullRatecustom property: added to fields that are sometimes null. It is the null fraction rounded up to two decimals.
Document. id and name are the cleaned contract name, or api_contract if nothing is left after cleaning. version is 1.0.0 and status is active. physicalName is the run URL cleaned the same way. The inferred document has no quality rules, logicalTypeOptions, enums or ranges.
Check a run against ODCS
Section titled “Check a run against ODCS”recon contract check <CONTRACT> <RUN_ID>The contract file must parse as ODCS with apiVersion, kind, id, name, version and at least one schema object. kind must be DataContract (any case). status is optional.
Recon checks the response against the first schema object only. It finds rows the same way as inference. If the schema has reconJsonPath, it reads rows from that key first.
For each row and each declared property:
| Code | When |
|---|---|
DK_REQUIRED_NULL |
The property is required or primaryKey and the value is missing or null. |
DK_TYPE_MISMATCH |
The value’s type is not compatible with logicalType. |
DK_DUPLICATE_KEY |
The property is unique or primaryKey and the value already appeared in an earlier row. |
DK_RANGE_MIN |
logicalTypeOptions.minimum is set and the number is below it. |
DK_RANGE_MAX |
logicalTypeOptions.maximum is set and the number is above it. |
DK_ENUM_MISMATCH |
logicalTypeOptions.enum is set and the string is not in it. |
DK_UNEXPECTED_COLUMN |
Strict mode is on and the row has a key the schema does not declare. |
DK_NO_ROWS |
No object rows were found. |
DK_INVALID_CONTRACT |
The document has no schema object. |
Compatible types: the same type, anything when the contract says any, integer where number is expected, date where timestamp is expected, and date or timestamp where string is expected. logicalType names are read case-insensitively, and common aliases work: text, varchar, char, uuid for string; int, bigint, smallint, int32, int64 for integer; float, double, decimal, numeric, real for number; bool; datetime, timestamptz; list; struct, map, json, jsonb. Any other name is treated as any.
Strict mode is on when the document or the first schema object has a custom property strict with the boolean value true:
customProperties:- property: strict value: trueContract `students_strict` check: INVALID (2 rows, 12 violation(s)) [DK_UNEXPECTED_COLUMN] email: Unexpected column `email` in strict mode... [DK_RANGE_MAX] gpa: Value 3.92 exceeds maximum 3.8... [DK_ENUM_MISMATCH] program: Value `MA` is not in allowed enum ["MDiv"]The check does not enforce pattern, minLength, maxLength or quality entries, even though the format can hold them.
Violations are reported per row, so a field that is wrong in every row appears once per row. In JSON output each violation has row_index (0-based), column, code and message. The report also has valid, contract_name and rows_checked.
Check a run against OpenAPI
Section titled “Check a run against OpenAPI”recon contract check-openapi <SPEC> <RUN_ID>The spec can be YAML or JSON, OpenAPI 3.0 or 3.1. Recon tries JSON first, then YAML. It validates the run’s status and JSON body.
- Path. Recon takes the path of the run URL. It also tries that path with each server URL’s path prefix removed. An exact match wins. Otherwise it picks the template with the most literal segments that matches segment by segment (
{param}and:parammatch any segment). - Method. The operation for the run’s method must exist on that path.
- Status. Recon looks for the exact code, then
2XX-style, then2xx-style, thendefault. A response$refis followed. - Schema. It uses the
application/jsonschema, or else the first media type whose name containsjson. If the operation has noresponses, or the response has no JSON schema, the run is valid.
OpenAPI check (GET /v1/students -> 200): VALID (0 violation(s))Supported schema keywords:
| Keyword | Notes |
|---|---|
$ref |
Local references (#/...) only. Cycles are skipped. |
allOf, anyOf, oneOf |
oneOf needs exactly one matching branch. |
type |
A string or a list. OpenAPI 3.0 nullable: true adds null. number also accepts integers. After a type mismatch, no other keyword is checked for that value. |
enum |
|
minimum, maximum |
Boolean exclusiveMinimum and exclusiveMaximum (3.0 style) are honoured. |
exclusiveMinimum, exclusiveMaximum |
Numeric form (3.1 style). |
minLength, maxLength |
Counted in characters. |
pattern |
A pattern that does not compile is ignored. |
format |
date, date-time, uuid, email, uri and url are checked. Other formats always pass. |
minItems, maxItems, items |
|
required, properties |
|
additionalProperties |
false flags extra keys. A schema validates them. |
Violation codes:
| Code | Message |
|---|---|
OPENAPI_INVALID_SPEC |
OpenAPI document is missing top-level `paths` object |
OPENAPI_PATH_NOT_FOUND |
No OpenAPI path template matches `{url}` |
OPENAPI_METHOD_NOT_FOUND |
OpenAPI path `{path}` does not define `{METHOD}` |
OPENAPI_STATUS_UNDOCUMENTED |
HTTP status {status} is not documented under `responses` |
OPENAPI_UNRESOLVED_REF |
Unresolved OpenAPI `$ref`: `{ref}` |
OPENAPI_ANY_OF |
Value at `{path}` did not satisfy any branch of `anyOf` |
OPENAPI_ONE_OF |
Value at `{path}` matched {n} branches of `oneOf` (expected 1) |
OPENAPI_TYPE_MISMATCH |
Expected type [{types}], got `{actual}` |
OPENAPI_ENUM_MISMATCH |
Value {value} is not in allowed enum [...] |
OPENAPI_MINIMUM |
Value {num} violates minimum {min} |
OPENAPI_EXCLUSIVE_MINIMUM |
Value {num} must be > {min} |
OPENAPI_MAXIMUM |
Value {num} violates maximum {max} |
OPENAPI_EXCLUSIVE_MAXIMUM |
Value {num} must be < {max} |
OPENAPI_MIN_LENGTH |
String length {n} is less than minLength {min} |
OPENAPI_MAX_LENGTH |
String length {n} exceeds maxLength {max} |
OPENAPI_PATTERN |
String `{s}` does not match pattern `{pattern}` |
OPENAPI_FORMAT |
String `{s}` does not match format `{format}` |
OPENAPI_MIN_ITEMS |
Array has {n} item(s), below minItems {min} |
OPENAPI_MAX_ITEMS |
Array has {n} item(s), above maxItems {max} |
OPENAPI_REQUIRED_MISSING |
Missing required property `{key}` |
OPENAPI_ADDITIONAL_PROPERTY |
Unexpected additional property `{key}` |
Every violation has a json_path such as $.students[0].gpa. The JSON report also has valid, matched_path, matched_method (lowercase) and matched_status:
{ "valid": false, "matched_path": "/v1/students", "matched_method": "get", "matched_status": "200", "violations": [ { "json_path": "$.students[0].student_id", "code": "OPENAPI_REQUIRED_MISSING", "message": "Missing required property `student_id`" },...Two results you may hit with an exported spec:
OpenAPI check (POST /v1/enrollments -> 201): INVALID (1 violation(s)) [OPENAPI_STATUS_UNDOCUMENTED] $: HTTP status 201 is not documented under `responses`This run belongs to Create Enrollment, whose operation was replaced by another request on the same path and method.
OpenAPI check (GET http://127.0.0.1:4401/_sandbox/local/v1/students -> 200): INVALID (1 violation(s)) [OPENAPI_PATH_NOT_FOUND] $: No OpenAPI path template matches `http://127.0.0.1:4401/_sandbox/local/v1/students`This spec has no servers entry with the /_sandbox/local prefix, so the full path /_sandbox/local/v1/students matches nothing. Add a matching servers URL to the spec to fix this.
To validate every response during a test run, use recon test --openapi-spec. See Send & Test.
Errors and exit codes
Section titled “Errors and exit codes”| Command | Exit code | When |
|---|---|---|
export openapi, contract infer |
0 |
Success. |
contract check, contract check-openapi |
0 |
The run is valid. |
contract check, contract check-openapi |
1 |
The run has violations. |
| all | 2 |
A runtime error (below). |
Runtime errors print E_CLI_RUNTIME with the message:
| Message | Cause |
|---|---|
run `ID` not found |
No run with that ID. |
response body is not valid JSON |
The run’s body is not JSON. |
failed to read `PATH` |
The contract or spec file cannot be read. |
YAML error: missing field `apiVersion`: missing field `apiVersion` |
A required ODCS field is missing. The field name is printed twice. |
invalid ODCS contract: expected kind `DataContract`, found `Nope` |
Wrong kind. |
invalid ODCS contract: ODCS document must contain at least one schema object |
Empty schema. |
invalid ODCS contract: samples contain no JSON objects to infer schema properties |
infer found no object rows. |
YAML error: ... |
The spec is neither JSON nor YAML. |
Also available via
Section titled “Also available via”HTTP (see HTTP API):
| Route | Body | Returns |
|---|---|---|
POST /api/v1/openapi/export |
{"title": "...", "version": "..."}, both optional |
{"spec", "yaml", "endpoints_count"}. Always airlocked. |
POST /api/v1/openapi/check |
{"spec_yaml": "...", "run_id": "..."} |
The OpenAPI report |
POST /api/v1/contracts/infer |
{"run_id": "..."} or {"json_text": "..."}, plus optional name |
The inferred contract. With json_text the name defaults to api_contract. |
POST /api/v1/contracts/check |
{"yaml": "...", "run_id": "..."} or json_text in place of run_id |
The ODCS report |
MCP (see MCP Tools): recon_export_openapi (title, version; always airlocked) and recon_check_openapi (run_id, plus spec_yaml or a workspace-relative spec_path).
Web Studio: the response panel’s “Drift & ODCS” tab has “Infer ODCS v3.2.0 YAML”, “Validate Run”, “Export OpenAPI 3.1 YAML”, “Validate Active Run” and “Copy YAML”. See Web Studio.