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.
- Existing APIs may not follow your latest standards and fixing them might not be an option. For instance, changing a property's name from
camelCasemight fix a failing Spectral lint rule, but it also introduces a breaking change. Catch-22
- 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
ruleset: - spectral: added: - pagination.spectral.yml - latest-naming.spectral.yml always: - 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.
ruleset: - spectral: added: - pagination.spectral.yml # local file - https://raw.github.com/gist/spectral-rule.yml # url to yaml - https://raw.github.com/gist/spectral-custom.js # 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