Enforce an API style guide in CI with Spectral: custom rules that stop bad OpenAPI before it merges
Every API program starts with a style guide document, and most end with it unread in a wiki while specs quietly grow duplicate operationId s, 200 responses with no body, GET requests that take secrets in the query string, and a dozen subtly different error shapes. Linting turns the guide into something that actually runs: a machine-readable ruleset that fails the pull request. Spectral is the…
Every API program begins with a style guide document, but often ends up unread on a wiki while specifications accumulate duplicate operationId s, 200 responses lacking bodies, GET requests containing secrets in query strings, and numerous distinct error shapes. Linting turns the guide into a machine-readable set of rules that will prevent the pull request from merging.
Spectral, the standard OpenAPI linter for this task, provides the value not from its built-in rules but from encoding your team's conventions once and enforcing them constantly. Run it locally and in Continuous Integration (CI) pipelines to ensure consistency. Spectral takes a ruleset file (in YAML or JavaScript format) and checks one or more documents: install the Spectral CLI using npm and run a lint command with the ruleset specified in the YAML file.
A minimal CI step can fail the build on errors while allowing warnings to pass through. Add the same command to a pre-commit hook so that authors receive feedback before they submit their pull request.
Begin by extending the OpenAPI recommended rules, then convert your style guide into explicit rules. Create a rules file (openapi/.spectral.yaml) that extends the spectral:oas rules and defines your own rules. For example, enforce proper documentation completeness (warnings during rollout), operationId conventions (operationId must be lowerCamelCase and verb-first, error), tag hygiene (Every used tag must be declared in the root tags array), error and response contract (Every 4xx/5xx response must reference the ProblemDetail schema), no secrets in query parameters, consistency (prefer an object envelope for top-level arrays), and array responses wrapped.
Custom functions can be written for cross-field rules, such as ensuring every write operation that returns 202 also documents a Location header, and every enum used in a response has an unknown-value policy note. In these custom functions, use JSONPath-plus syntax for cross-field logic and define a given selector, assertion, and severity for each rule.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.