Example Payload Management
Effective OpenAPI & AsyncAPI Schema Authoring relies on precise sample data to accelerate developer onboarding. This workflow decouples verbose examples from core definitions. It enforces consistency via CI pipelines and optimizes portal rendering for versioned APIs.
Implementation objectives:
- Decouple inline examples to external YAML/JSON files
- Implement Spectral rules for payload validation
- Automate CI/CD checks for schema drift
- Optimize portal rendering with lazy-loaded samples
Externalizing Payload References
Replace inline example and examples blocks with $ref pointers to maintain spec readability. This approach aligns with Structuring OpenAPI Paths best practices and enables independent versioning of sample data. Parallel directory structures reduce parser overhead and prevent merge conflicts during collaborative editing.
Implementation steps:
- Use
$ref: ./examples/v1/pet-create.yamlsyntax for all payload samples - Maintain strict directory parity between spec endpoints and example files
- Configure bundlers to resolve relative paths during build time
- Support multi-format outputs (JSON, XML, YAML) per media type
Configuration: YAML/JSON directory layout, OpenAPI bundler setup (redocly bundle or swagger-cli).
CI-Driven Validation & Spectral Integration
Enforce payload accuracy and schema compliance by integrating linting rules directly into pull request workflows. Proper Defining JSON Schema Components ensures examples match required fields, data types, and enum constraints before merging. Automated validation catches drift early and guarantees contract reliability.
Implementation steps:
- Configure Spectral
truthyandpatternrules for example presence - Validate against
x-examplesin AsyncAPI message payloads - Fail CI pipelines immediately on type mismatches or missing required fields
- Cache validation artifacts to accelerate subsequent pipeline runs
Configuration: .spectral.yaml ruleset, GitHub Actions workflow definition, Node.js runtime.
Version-Aware Portal Rendering
Automate the injection of correct example payloads into developer portals based on API version tags. This prevents stale documentation and ensures consumers interact with Managing large example payloads in API specs without manual intervention. Dynamic routing guarantees accurate try-it-out experiences across releases.
Implementation steps:
- Map semantic version tags to dedicated example directories
- Configure portal generators (Redoc, Stoplight, Scalar) for dynamic injection
- Implement fallback logic to gracefully handle missing versioned samples
- Enable interactive consoles with pre-filled, schema-compliant payloads
Configuration: Portal generator config (redocly.yaml, stoplight.config.json), environment variable mapping.
Configuration Examples
Spectral Validation Ruleset
# .spectral.yaml
rules:
response-has-example:
description: 'Ensure JSON responses include valid examples.'
severity: error
given: "$.paths[*].responses[*].content['application/json']"
then:
field: examples
function: truthy
example-matches-schema:
description: 'Validate example structure against schema.'
severity: error
given: "$.paths[*].responses[*].content['application/json'].schema"
then:
field: examples
function: schema
Context & Output: This ruleset enforces mandatory example presence and structural alignment with the defined JSON Schema during CI validation. Running spectral lint openapi.yaml --ruleset .spectral.yaml exits with code 1 and prints precise line numbers for any missing or malformed examples.
GitHub Actions CI Workflow
# .github/workflows/spec-validation.yml
name: Validate & Bundle Spec
on: [pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate & Bundle Spec
run: |
npm install -g @stoplight/spectral-cli@6.11.1 @redocly/cli@1.18.1
spectral lint openapi.yaml --ruleset .spectral.yaml
redocly bundle openapi.yaml --output dist/openapi-bundled.yaml --ext yaml
echo 'Examples validated and spec bundled successfully.'
Context & Output: This workflow automates linting and bundling, ensuring external references resolve correctly and examples pass validation rules before merging. Successful execution produces a consolidated dist/openapi-bundled.yaml artifact ready for portal deployment.
Common Pitfalls
- Inline Example Bloat: Embedding large JSON payloads directly in the spec file increases file size, slows parser performance, and triggers frequent merge conflicts. Externalize immediately.
- Schema-Example Drift: Failing to update examples when schemas evolve breaks try-it-out consoles and causes integration failures. Enforce CI validation to catch mismatches.
- Broken Relative References in CI: Runners execute from isolated working directories, causing
$refpaths to fail without explicit base path configuration. Use absolute paths relative to the repo root or configure--baseflags in bundlers.
FAQ
Should I use example or examples in OpenAPI 3.1?
Use examples (plural) to provide multiple media-type variants or versioned samples. The singular example is deprecated in favor of examples for robust multi-format support.
How do I validate external example files against schemas in CI?
Use Spectral’s schema function with custom resolvers or integrate ajv-cli to validate external JSON/YAML payloads against the compiled schema before merging.
Can AsyncAPI handle large message examples efficiently?
Yes. Externalize payloads via $ref in the payload object and leverage the AsyncAPI Generator’s template caching to render samples on-demand in the portal.