पाठ 17 / 25

Validating and Linting OpenAPI Documents

Validate documents and enforce style rules with Spectral or Redocly.

Catching mistakes and inconsistencies early

Two kinds of checks protect API descriptions. Validation checks that the document conforms to the OpenAPI Specification: correct structure, valid $ref targets, required fields present. Linting checks style and quality rules beyond the spec: every operation has an operationId, summary and tags; paths use kebab-case; properties use camelCase; every operation documents 4XX errors; examples are valid against schemas; no unused components; descriptions present; security defined on every non-public operation. Spectral (from Stoplight) is a popular, rule-based linter with built-in OpenAPI and AsyncAPI rulesets and custom rules written in YAML or JavaScript; Redocly CLI offers linting, bundling of multi-file documents and previews. Run linters in the editor (VS Code extensions), as pre-commit hooks and in CI, failing pull requests on errors. Start with recommended rulesets, then add organisation-specific rules from your API style guide, and keep warnings few enough that people read them.

A Spectral ruleset with custom rules

Built-in OpenAPI rules plus two house-style rules.

# .spectral.yaml
extends: ["spectral:oas"]
rules:
  operation-operationId: error          # built-in rule, raised to error
  operation-tags: error

  paths-kebab-case:
    description: Paths must be kebab-case
    severity: error
    given: $.paths[*]~
    then:
      function: pattern
      functionOptions:
        match: "^(/[a-z0-9-]+|/\\{[a-zA-Z]+\\})+$"

  must-document-errors:
    description: Every operation should document at least one 4XX response
    severity: warn
    given: $.paths[*][get,post,put,patch,delete].responses
    then:
      function: schema
      functionOptions:
        schema:
          type: object
          patternProperties: { "^4[0-9X]{2}$": {} }
          minProperties: 1

# run locally or in CI:
# npx @stoplight/spectral-cli lint api/openapi.yaml --fail-severity=error
# npx @redocly/cli lint api/openapi.yaml && npx @redocly/cli bundle api/openapi.yaml -o dist/openapi.yaml

A spell checker and a style editor

Validation is the spell checker: it catches words that do not exist. Linting is the editor who knows your publication's style guide and points out sentences that are correct but inconsistent.

त्वरित जाँच: What does linting an OpenAPI document check beyond spec validation?

  • Whether the server is running
  • Style and quality rules such as naming conventions, required descriptions and documented errors
  • Database indexes
  • Network latency
Answer

Style and quality rules such as naming conventions, required descriptions and documented errors — Linters enforce organisation-specific conventions on top of structural validity.