Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Validation and Contract Testing

Linting OpenAPI with Spectral

Lint OpenAPI documents with Spectral: built-in rulesets, severities, custom rules with given and then, overrides and CI. Includes a runnable mini rule engine stand-in.

A spec can be valid (it follows the OpenAPI schema) and still be bad: no operationId, no descriptions, inconsistent naming, paths in camelCase next to paths in snake_case. Linting checks the quality and style of a document beyond basic validity. The most popular linter is Spectral by Stoplight; Redocly CLI offers a similar lint command with its own rules.

Spectral is a Node program, so it cannot run on this website. The commands and rulesets below are read-only. A mini rule engine written in Python lets you try the core idea (given + then) here.

Install and run

Terminal
npm install --save-dev @stoplight/spectral-cli

# a one-line ruleset that enables the built-in OpenAPI rules
echo 'extends: ["spectral:oas"]' > .spectral.yaml

npx spectral lint openapi.yaml

The output lists each problem with a file position, a severity (error, warning, information, hint), a rule code and a JSON path. The command exits with a non-zero code when it finds errors, which makes it usable as a CI gate. Use --fail-severity warn to also fail on warnings.

What the built-in ruleset checks

The spectral:oas ruleset has dozens of rules. Examples:

Rule What it catches
operation-operationId Operation without operationId
operation-operationId-unique Duplicate IDs
operation-description Missing description
operation-tags Operation with no tags
info-contact, info-description Missing metadata
no-$ref-siblings Keys next to a $ref that are ignored
oas3-valid-schema-example An example that does not match its schema
path-params Path template variables not declared as parameters
no-eval-in-markdown, no-script-tags-in-markdown Dangerous content in descriptions

Writing your own rules

A rule has two parts: given selects parts of the document with a JSONPath expression, and then applies a function to a field of each selected part.

YAML
# .spectral.yaml
extends: ["spectral:oas"]
rules:
  paths-kebab-case:
    description: Path segments must be lowercase kebab-case
    severity: error
    given: $.paths[*]~
    then:
      function: pattern
      functionOptions:
        match: "^(/([a-z0-9]+(-[a-z0-9]+)*|\\{[A-Za-z][A-Za-z0-9]*\\}))+$"

  operation-summary-required:
    description: Every operation needs a short summary
    severity: warn
    given: $.paths[*][get,post,put,patch,delete]
    then:
      field: summary
      function: truthy

  operation-ids-camel-case:
    severity: error
    given: $.paths[*][*].operationId
    then:
      function: casing
      functionOptions:
        type: camel

Common core functions: truthy, falsy, defined, undefined, pattern, casing, length, enumeration, alphabetical, schema and xor. You can also write custom functions in JavaScript. A trailing ~ in a JSONPath returns the key name instead of the value, which is how a rule can check path strings themselves.

To disable or downgrade a built-in rule, list it with a new severity or off:

YAML
rules:
  info-contact: off
  operation-tags: warn

Overrides for legacy parts

When you adopt linting on an old spec you may not be able to fix everything at once. Use overrides to relax a rule for a legacy file or path, and fix problems in steps. Never switch linting off completely: a green build that checks nothing is worse than a red one.

A mini rule engine

The stand-in below implements given (a simplified path selector) and three functions (truthy, pattern, casing), then runs a ruleset against a spec and prints Spectral-style messages.

Python Stand-in: a tiny Spectral-style rule engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real Spectral resolves full JSONPath, follows $ref, reports line numbers and supports your own JavaScript functions, but the control flow is the same.

Putting linting in the workflow

  • Run it in the editor (the Spectral VS Code extension) for instant feedback.
  • Run it in a pre-commit hook and in CI on every pull request.
  • Share one ruleset across APIs through an npm package or a URL, with extends, so all teams follow the same style guide.
  • Lint the bundled document if you split your spec into many files (see splitting and bundling).

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. In a Spectral rule, what does 'given' do?

    given selects nodes; then applies a function to a field of those nodes.
  2. 2. A spec is valid OpenAPI but has no operationIds. Which tool finds this?

    Validity checks structure. Linting enforces quality rules such as requiring operationId.
  3. 3. How can you make CI fail when Spectral reports warnings too?

    By default only errors fail the run; --fail-severity lowers the threshold.

Summary

  • Linting checks quality and style beyond schema validity.
  • Spectral rules combine given (JSONPath) with then (field and function), with severities from error to hint.
  • Extend spectral:oas, add your own rules and use overrides to adopt gradually.
  • Run linting in the editor, pre-commit and CI.
  • The Python engine is a stand-in showing the rule-evaluation loop.

Next: Validating requests and responses