Running Spectral Rules

Spectral (opens in a new tab) is a great open source API linter that many teams use to automate their API Style Guides. Linting an OpenAPI spec works great when you are designing a brand-new API, but it presents some challenges (opens in a new tab) if you apply those style guides to existing/legacy APIs.

  1. Existing APIs may not follow your latest standards and fixing them might not be an option. For instance, changing a property's name from snake_case to camelCase might fix a failing Spectral lint rule, but it also introduces a breaking change. Catch-22
  2. Making developers change their API design and implementation months/years after they build the API can disrupt teams across your company. Everyone should have to make important changes (like adding security), but most other style guides do not need to apply to existing APIs immediately.

Optic solves this limitation of Spectral by letting you set some rules to always run, and other rules to only run on endpoints that are added.

  - spectral:
        - pagination.spectral.yml
        - latest-naming.spectral.yml
        - security.spectral.yml
        - metadata.spectral.yml

Optic uses the spectral CLI under the hood. Any ruleset that runs with the -r --ruleset flag can be used with Optic (opens in a new tab), including modules, urls, and local YAML files.

  - spectral:
        - pagination.spectral.yml # local file
        - # url to yaml
        - # url to js
        - our-api-standards # node module

Now when you use optic diff or optic run Spectral is used to run these rules. Optic computes the changes between your current branch and the main branch. Now that it knows about your API changes, Optic can run your added Spectral rules on additions, and your always Spectral rules on everything else:

optic diff --check openapi.yaml --base main


added string[] (optional):

A list of spectral rules to apply on additions.

addedOrChanged string[] (optional):

A list of spectral rules to apply on additions or changes.

changed string[] (optional):

A list of spectral rules to apply on changes.

always string[] (optional):

A list of spectral rules to always run.

exclude_operations_with_extension (optional):

Exclude operations with extensions