API Contract Testing — validate an OpenAPI spec against expected endpoints
Load this skill when you need to check that a running API (or a spec on
disk) actually matches the contract it promises. It is the verification
counterpart of api-doc-generator (which writes the spec) and
test-generator (which writes the tests): this skill checks the spec
against a manifest of expected endpoints and, optionally, against the live
API.
The tool is pure Python 3 stdlib — no PyYAML, no requests, no pip
install. It reads an OpenAPI 3.x document from a file (.json or .yaml)
or a URL, enumerates every declared operation (under paths and webhooks),
checks the spec's internal consistency, and compares it against an optional
manifest file. In --offline mode it never touches the network; in live mode
it probes each manifest endpoint over HTTP and compares the actual status
code with the expected one.
Triggers
Load this skill when the request matches any of these (EN / RU):
- "api contract testing", "contract test", "check the API against the spec"
- "validate openapi spec", "spec vs manifest", "endpoint coverage"
- "проверь контракт API", "тест контракта", "сверь спецификацию с API"
- "валидация openapi", "проверка эндпоинтов", "контрактное тестирование"
- "does the API match the spec", "missing endpoints", "expected status codes"
DO NOT USE FOR: generating the OpenAPI spec (use api-doc-generator); writing the tests (use test-generator). This skill only checks contracts, it does not author them.
The api_contract.py script
scripts/api_contract.py — pure Python 3 stdlib (no dependencies).
| Mode |
Command |
| Offline, JSON report |
python3 api_contract.py --spec openapi.json --offline --json |
| Offline + manifest |
python3 api_contract.py --spec openapi.yaml --manifest endpoints.txt --offline |
| Live checks |
python3 api_contract.py --spec openapi.json --manifest endpoints.txt --base-url https://api.example.com |
| Spec from URL |
python3 api_contract.py --spec-url https://example.com/openapi.json --manifest endpoints.txt |
Flags
--spec <path> — OpenAPI spec file (.json, .yaml, .yml). YAML is
parsed by a built-in subset parser (see Limitations).
--spec-url <URL> — fetch the spec over HTTP(S) with urllib.request.
The format is detected by the URL extension, then by trying JSON first
and falling back to the YAML parser.
--base-url <URL> — base URL for live checks. Resolution order:
--base-url → spec servers[0].url → env APITEST_BASE_URL.
--manifest <file> — expected contract, one METHOD path [expected_status]
per line (blank lines and # comments ignored). expected_status may be an
exact code (200), a class wildcard (2xx), or default.
--json — emit the report as a JSON object on stdout (machine-readable).
--offline — no network at all: validate spec internal consistency and
compare the manifest against the spec only.
Exit codes
| Code |
Meaning |
0 |
conformant (or offline-ok) |
1 |
contract violations detected (missing endpoints, mismatched statuses) |
2 |
spec/parse/run error (unreadable file, invalid JSON/YAML, bad manifest, live-check network failure) |
Report structure
The report is always the same JSON structure; --json prints it verbatim,
without --json it is rendered as text.
{
"endpoints_count": 2,
"missing_from_spec": [{"method": "DELETE", "path": "/pets", "expected": "204"}],
"contract_violations": [{"method": "GET", "path": "/pets", "expected": "200", "actual": "404", "severity": "error"}],
"conformant": false,
"errors": []
}
endpoints_count — number of operations declared in the spec (paths + webhooks).
missing_from_spec — manifest entries that do not exist in the spec.
contract_violations — severity: "error" breaks the contract (missing
expected status, unresolved $ref); severity: "warning" is informational
(duplicate operation, operation without responses, empty spec).
conformant — true iff no errors, no missing endpoints and no
error-severity violations.
errors — fatal problems (parse failures, live-check network errors).
Usage example (typical)
# 1. Offline sanity check of a spec: is it internally consistent?
python3 skills/api-contract-testing/scripts/api_contract.py \
--spec openapi.yaml --offline --json
# 2. Does the spec cover everything the product promised?
python3 skills/api-contract-testing/scripts/api_contract.py \
--spec openapi.json --manifest endpoints.txt --offline --json
# 3. Live: does the running API actually return the promised statuses?
python3 skills/api-contract-testing/scripts/api_contract.py \
--spec openapi.json --manifest endpoints.txt --base-url https://api.example.com
# 4. Machine-readable gate for CI (exit code drives the pipeline)
python3 skills/api-contract-testing/scripts/api_contract.py \
--spec openapi.yaml --manifest endpoints.txt --offline --json \
| python3 -c 'import json,sys; sys.exit(0 if json.load(sys.stdin)["conformant"] else 1)'
Manifest format
# expected API contract
GET /pets 200
POST /pets 201
DELETE /pets/{id} 204
GET /health 2xx
expected_status is optional — a line without it only asserts that the
endpoint exists in the spec. Wildcards (2xx, 4xx) match any code in that
class; default matches the spec's default response key.
Interpretation guidance
conformant: true — the spec is internally consistent and every
manifest endpoint exists with the expected status (offline), or the live
API returned the expected statuses (live mode).
missing_from_spec non-empty — the product promised endpoints the spec
does not declare. Either the spec is stale (regenerate with
api-doc-generator) or the manifest is wrong.
contract_violations with severity: "error" — a promised status is
not declared in the spec (offline) or the live API returned a different
status (live). This is the signal that breaks the contract.
severity: "warning" — spec hygiene issues (duplicate operations,
operations without responses, unresolved $ref). They do not fail the run
but should be fixed.
errors non-empty — the tool could not do its job (file not found,
invalid JSON/YAML, bad manifest line, network failure). Exit code 2.
Integration notes
- CI gate: use
--json and pipe through a JSON check, or rely on the
exit code directly (0/1/2).
- Base URL: prefer
servers[0].url in the spec; override with
--base-url or APITEST_BASE_URL for per-environment runs.
- Live mode is manifest-driven: only endpoints listed in the manifest are
probed; the spec itself is never called. Use
--offline in CI when the API
is not deployed yet.
- Companion skills:
api-doc-generator produces the spec,
test-generator produces the tests — this skill verifies the contract
between them.
Limitations
- YAML support is a subset, not a full YAML parser. The built-in parser
handles block mappings/sequences, flow collections (
{...}, [...]),
quoted scalars, comments and block scalars (|, >). It does not
support anchors/aliases (&a, *a), tags (!!str), multi-document
streams (--- separators), or exotic scalar quoting. If your spec uses
those, convert it to JSON (python3 -c 'import yaml,json,sys; print(json.dumps(yaml.safe_load(sys.stdin)))' with PyYAML available) and pass the .json file.
- No schema validation — the tool checks structure and consistency, not
whether every field conforms to the OpenAPI meta-schema.
- Live checks are status-code only — request/response bodies are not
validated against the spec's schemas.
- Path matching is exact —
/pets and /pets/ are treated as different
paths; template parameters (/pets/{id}) must match literally.
Canonical analogues
Full source depth — in references/canonical-patterns.md. Backbone:
Installation
# For opencode
cp -r skills/api-contract-testing ~/.config/opencode/skills/
# For other agents
# Copy the skill folder to your skills directory; requires Python 3 only.
Note: the tool is read-only — it never modifies the spec, the manifest
or the API. It reports; you decide what to fix.
1---2name: api-contract-testing3description: Validate an API contract against an OpenAPI 3.x specification (JSON or YAML) and an optional manifest of expected endpoints. Script api_contract.py enumerates operations (paths + webhooks), checks spec internal consistency (unresolved $refs, duplicates, missing responses), compares the manifest against the spec offline, and in live mode probes each manifest endpoint over HTTP and compares the actual status with the expected one. Pure Python 3 stdlib (argparse, json, pathlib, sys, urllib.request) with a built-in minimal YAML subset parser — no PyYAML, no requests. Emits a machine-readable JSON report (endpoints_count, missing_from_spec, contract_violations, conformant, errors) and uses exit codes 0/1/2. Closes the loop for api-doc-generator and test-generator.4license: MIT5---67# API Contract Testing — validate an OpenAPI spec against expected endpoints89Load this skill when you need to **check that a running API (or a spec on10disk) actually matches the contract it promises**. It is the verification11counterpart of `api-doc-generator` (which *writes* the spec) and12`test-generator` (which *writes* the tests): this skill *checks* the spec13against a manifest of expected endpoints and, optionally, against the live14API.1516The tool is **pure Python 3 stdlib** — no PyYAML, no requests, no pip17install. It reads an OpenAPI 3.x document from a file (`.json` or `.yaml`)18or a URL, enumerates every declared operation (under `paths` and `webhooks`),19checks the spec's internal consistency, and compares it against an optional20manifest file. In `--offline` mode it never touches the network; in live mode21it probes each manifest endpoint over HTTP and compares the actual status22code with the expected one.2324## Triggers2526Load this skill when the request matches any of these (EN / RU):2728- "api contract testing", "contract test", "check the API against the spec"29- "validate openapi spec", "spec vs manifest", "endpoint coverage"30- "проверь контракт API", "тест контракта", "сверь спецификацию с API"31- "валидация openapi", "проверка эндпоинтов", "контрактное тестирование"32- "does the API match the spec", "missing endpoints", "expected status codes"3334**DO NOT USE FOR**: generating the OpenAPI spec (use `api-doc-generator`); writing the tests (use `test-generator`). This skill only *checks* contracts, it does not author them.3536---3738## The api_contract.py script3940`scripts/api_contract.py` — pure Python 3 stdlib (no dependencies).4142| Mode | Command |43|---|---|44| Offline, JSON report | `python3 api_contract.py --spec openapi.json --offline --json` |45| Offline + manifest | `python3 api_contract.py --spec openapi.yaml --manifest endpoints.txt --offline` |46| Live checks | `python3 api_contract.py --spec openapi.json --manifest endpoints.txt --base-url https://api.example.com` |47| Spec from URL | `python3 api_contract.py --spec-url https://example.com/openapi.json --manifest endpoints.txt` |4849### Flags5051- `--spec <path>` — OpenAPI spec file (`.json`, `.yaml`, `.yml`). YAML is52 parsed by a built-in subset parser (see Limitations).53- `--spec-url <URL>` — fetch the spec over HTTP(S) with `urllib.request`.54 The format is detected by the URL extension, then by trying JSON first55 and falling back to the YAML parser.56- `--base-url <URL>` — base URL for live checks. Resolution order:57 `--base-url` → spec `servers[0].url` → env `APITEST_BASE_URL`.58- `--manifest <file>` — expected contract, one `METHOD path [expected_status]`59 per line (blank lines and `#` comments ignored). `expected_status` may be an60 exact code (`200`), a class wildcard (`2xx`), or `default`.61- `--json` — emit the report as a JSON object on stdout (machine-readable).62- `--offline` — no network at all: validate spec internal consistency and63 compare the manifest against the spec only.6465### Exit codes6667| Code | Meaning |68|---|---|69| `0` | conformant (or offline-ok) |70| `1` | contract violations detected (missing endpoints, mismatched statuses) |71| `2` | spec/parse/run error (unreadable file, invalid JSON/YAML, bad manifest, live-check network failure) |7273### Report structure7475The report is always the same JSON structure; `--json` prints it verbatim,76without `--json` it is rendered as text.7778```json79{80 "endpoints_count": 2,81 "missing_from_spec": [{"method": "DELETE", "path": "/pets", "expected": "204"}],82 "contract_violations": [{"method": "GET", "path": "/pets", "expected": "200", "actual": "404", "severity": "error"}],83 "conformant": false,84 "errors": []85}86```8788- `endpoints_count` — number of operations declared in the spec (paths + webhooks).89- `missing_from_spec` — manifest entries that do not exist in the spec.90- `contract_violations` — `severity: "error"` breaks the contract (missing91 expected status, unresolved `$ref`); `severity: "warning"` is informational92 (duplicate operation, operation without responses, empty spec).93- `conformant` — `true` iff no errors, no missing endpoints and no94 error-severity violations.95- `errors` — fatal problems (parse failures, live-check network errors).9697## Usage example (typical)9899```bash100# 1. Offline sanity check of a spec: is it internally consistent?101python3 skills/api-contract-testing/scripts/api_contract.py \102 --spec openapi.yaml --offline --json103104# 2. Does the spec cover everything the product promised?105python3 skills/api-contract-testing/scripts/api_contract.py \106 --spec openapi.json --manifest endpoints.txt --offline --json107108# 3. Live: does the running API actually return the promised statuses?109python3 skills/api-contract-testing/scripts/api_contract.py \110 --spec openapi.json --manifest endpoints.txt --base-url https://api.example.com111112# 4. Machine-readable gate for CI (exit code drives the pipeline)113python3 skills/api-contract-testing/scripts/api_contract.py \114 --spec openapi.yaml --manifest endpoints.txt --offline --json \115 | python3 -c 'import json,sys; sys.exit(0 if json.load(sys.stdin)["conformant"] else 1)'116```117118### Manifest format119120```121# expected API contract122GET /pets 200123POST /pets 201124DELETE /pets/{id} 204125GET /health 2xx126```127128`expected_status` is optional — a line without it only asserts that the129endpoint exists in the spec. Wildcards (`2xx`, `4xx`) match any code in that130class; `default` matches the spec's `default` response key.131132## Interpretation guidance133134- **`conformant: true`** — the spec is internally consistent and every135 manifest endpoint exists with the expected status (offline), or the live136 API returned the expected statuses (live mode).137- **`missing_from_spec` non-empty** — the product promised endpoints the spec138 does not declare. Either the spec is stale (regenerate with139 `api-doc-generator`) or the manifest is wrong.140- **`contract_violations` with `severity: "error"`** — a promised status is141 not declared in the spec (offline) or the live API returned a different142 status (live). This is the signal that breaks the contract.143- **`severity: "warning"`** — spec hygiene issues (duplicate operations,144 operations without responses, unresolved `$ref`). They do not fail the run145 but should be fixed.146- **`errors` non-empty** — the tool could not do its job (file not found,147 invalid JSON/YAML, bad manifest line, network failure). Exit code `2`.148149## Integration notes150151- **CI gate**: use `--json` and pipe through a JSON check, or rely on the152 exit code directly (`0`/`1`/`2`).153- **Base URL**: prefer `servers[0].url` in the spec; override with154 `--base-url` or `APITEST_BASE_URL` for per-environment runs.155- **Live mode is manifest-driven**: only endpoints listed in the manifest are156 probed; the spec itself is never called. Use `--offline` in CI when the API157 is not deployed yet.158- **Companion skills**: `api-doc-generator` produces the spec,159 `test-generator` produces the tests — this skill verifies the contract160 between them.161162## Limitations163164- **YAML support is a subset, not a full YAML parser.** The built-in parser165 handles block mappings/sequences, flow collections (`{...}`, `[...]`),166 quoted scalars, comments and block scalars (`|`, `>`). It does **not**167 support anchors/aliases (`&a`, `*a`), tags (`!!str`), multi-document168 streams (`---` separators), or exotic scalar quoting. If your spec uses169 those, convert it to JSON (`python3 -c 'import yaml,json,sys; print(json.dumps(yaml.safe_load(sys.stdin)))'` with PyYAML available) and pass the `.json` file.170- **No schema validation** — the tool checks structure and consistency, not171 whether every field conforms to the OpenAPI meta-schema.172- **Live checks are status-code only** — request/response bodies are not173 validated against the spec's schemas.174- **Path matching is exact** — `/pets` and `/pets/` are treated as different175 paths; template parameters (`/pets/{id}`) must match literally.176177## Canonical analogues178179Full source depth — in `references/canonical-patterns.md`. Backbone:180181<table>182<tr><th>Analog</th><th>What we borrow</th></tr>183<tr><td>Schemathesis</td><td>Spec-driven contract checking, property-based probing of declared responses</td></tr>184<tr><td>Dredd</td><td>Manifest/transaction-driven verification of endpoints against a live API</td></tr>185<tr><td>oasdiff</td><td>Spec internal-consistency and compatibility analysis</td></tr>186<tr><td>Spectral</td><td>Lint-style rules for spec hygiene (warnings vs. errors)</td></tr>187<tr><td>openapi-generator</td><td>Endpoint enumeration from paths + operations as the source of truth</td></tr>188</table>189190## Installation191192```bash193# For opencode194cp -r skills/api-contract-testing ~/.config/opencode/skills/195196# For other agents197# Copy the skill folder to your skills directory; requires Python 3 only.198```199200---201202> **Note**: the tool is read-only — it never modifies the spec, the manifest203> or the API. It reports; you decide what to fix.