UNPKG

11.7 kBMarkdownView Raw
1![Spectral logo](img/spectral-banner.png)
2
3[![Test Coverage](https://api.codeclimate.com/v1/badges/1aa53502913a428f40ac/test_coverage)](https://codeclimate.com/github/stoplightio/spectral/test_coverage)
4[![Maintainability](https://api.codeclimate.com/v1/badges/1aa53502913a428f40ac/maintainability)](https://codeclimate.com/github/stoplightio/spectral/maintainability)
5
6A flexible JSON object linter with out of the box support for OpenAPI v2 and v3
7
8## Features
9
10- Create custom rules to lint _any JSON object_
11- Use JSON paths to apply rules / functions to specific parts of your JSON objects
12- Built-in set of functions to help [build custom rules](#creating-a-custom-rule). Functions include pattern checks, parameter checks, alphabetical ordering, a specified number of characters, provided keys are present in an object, etc
13- [Create custom functions](#creating-a-custom-function) for advanced use cases
14- Optional ready to use rules and functions to validate and lint [OpenAPI v2 _and_ v3 documents](#example-linting-an-openapi-document)
15- Validate JSON with [Ajv](https://github.com/epoberezkin/ajv)
16
17## Installation
18
19### Local Installation
20
21```bash
22npm install @stoplight/spectral
23```
24
25### Global Installation
26
27```bash
28npm install -g @stoplight/spectral
29```
30
31Supports Node v8.3+.
32
33### Executable binaries
34
35For users without Node and/or NPM/Yarn, we provide standalone packages for all major platforms:
36
37- x64 Windows
38- x64 MacOS
39- x64 Linux
40
41You can find them [here](https://github.com/stoplightio/spectral/releases).
42Once downloaded, you can proceed with the standard procedure for running any CLI tool.
43
44```bash
45./spectral-macos lint petstore.yaml
46```
47
48Note, the binaries are *not* auto-updatable, therefore you will need to download a new version on your own.
49
50#### Installing binaries system-wide
51
52##### Linux
53
54```bash
55sudo mv ./spectral-linux /usr/local/bin/spectral
56```
57
58You may need to restart your terminal.
59Now, `spectral` command will be accessible in your terminal.
60
61Head over to [releases](https://github.com/stoplightio/spectral/releases) for the latest binaries.
62
63
64### Docker
65```bash
66docker run --rm -it stoplight/spectral lint "${URL}"`
67```
68
69## Usage
70
71### CLI
72
73Spectral can be run via the command-line:
74
75```bash
76spectral lint petstore.yaml
77```
78
79Other options include:
80
81``` text
82 -c, --config=config path to a config file
83 -e, --encoding=encoding text encoding to use
84 -f, --format=json|stylish formatter to use for outputting results
85 -h, --help show CLI help
86 -m, --maxResults=maxResults deprecated: use --max-results instead
87 -o, --output=output output to a file instead of stdout
88 -r, --ruleset=ruleset path to a ruleset file (supports remote files)
89 -s, --skip-rule=skip-rule ignore certain rules if they are causing trouble
90 -v, --verbose increase verbosity
91 --max-results=max-results [default: all] maximum results to show
92```
93
94> Note: The Spectral CLI supports both YAML and JSON.
95
96Currently, the CLI supports validation of OpenAPI documents and lints them based on our default ruleset. It does not support custom rulesets at this time. Although if you want to build and run custom rulesets outside of the CLI, see [Customization](#Customization).
97
98### Example: Linting an OpenAPI document
99
100Spectral includes a number of ready made rules and functions for OpenAPI v2 and v3 documents.
101
102This example uses the OpenAPI v3 rules to lint a document.
103
104```javascript
105const { Spectral } = require('@stoplight/spectral');
106const { oas3Functions, oas3Rules } = require('@stoplight/spectral/rulesets/oas3');
107// for YAML
108const { parseWithPointers } = require("@stoplight/yaml");
109const myOAS = parseWithPointers(`
110responses:
111 '200':
112 description: ''
113 schema:
114 $ref: '#/definitions/error-response'
115`)
116
117// an OASv3 document
118const myOAS = {
119 // ... properties in your document
120 responses: {
121 '200': {
122 description: '',
123 schema: {
124 $ref: '#/definitions/error-response',
125 },
126 },
127 },
128 // ... properties in your document
129};
130
131// create a new instance of spectral with all of the baked in rulesets
132const spectral = new Spectral();
133
134spectral.addFunctions(oas3Functions());
135spectral.addRules(oas3Rules());
136
137spectral.addRules({
138 // .. extend with your own custom rules
139});
140
141// run!
142spectral.run(myOAS).then(results => {
143 console.log(JSON.stringify(results, null, 4));
144});
145```
146
147You can also [add to these rules](#Creating-a-custom-rule) to create a customized linting style guide for your OpenAPI documents.
148
149The existing OAS rules are opinionated. There might be some rules that you prefer to change. We encourage you to create your rules to fit your use case. We welcome additions to the existing rulesets as well!
150
151## Rulesets
152
153You can find all about [rulesets here](docs/rulesets.md).
154
155## Advanced
156
157### Customization
158
159There are three key concepts in Spectral: **Rulesets**, **Rules** and **Functions**.
160
161- **Ruleset** is a container for a collection of rules and functions.
162- **Rule** filters your object down to a set of target values, and specify the function that should evaluate those values.
163- **Function** accept a value and return issue(s) if the value is incorrect.
164
165Think of a set of **rules** and **functions** as a flexible and customizable style guide for your JSON objects.
166
167#### Creating a custom rule
168
169Spectral has a built-in set of functions which you can reference in your rules. This example uses the `RuleFunction.PATTERN` to create a rule that checks that all property values are in snake case.
170
171```javascript
172const { RuleFunction, Spectral } = require('@stoplight/spectral');
173
174const spectral = new Spectral();
175
176spectral.addRules({
177 snake_case: {
178 summary: 'Checks for snake case pattern',
179
180 // evaluate every property
181 given: '$..*',
182
183 then: {
184 function: RuleFunction.PATTERN,
185 functionOptions: {
186 match: '^[a-z]+[a-z0-9_]*[a-z0-9]+$',
187 },
188 },
189 },
190});
191
192// run!
193spectral.run({name: 'helloWorld',}).then(results => {
194 console.log(JSON.stringify(results, null, 4));
195});
196
197// => outputs a single result since `helloWorld` is not snake_case
198// [
199// {
200// "code": "snake_case",
201// "message": "must match the pattern '^[a-z]+[a-z0-9_]*[a-z0-9]+$'",
202// "severity": 1,
203// "path": [
204// "name"
205// ]
206// }
207// ]
208```
209
210#### Creating a custom function
211
212Sometimes the built-in functions don't cover your use case. This example creates a custom function, `customNotThatFunction`, and then uses it within a rule, `openapi_not_swagger`. The custom function checks that you are not using a specific string (e.g., "Swagger") and suggests what to use instead (e.g., "OpenAPI").
213
214```javascript
215const { Spectral } = require('@stoplight/spectral');
216
217// custom function
218const customNotThatFunction = (targetValue, options) => {
219 const { match, suggestion } = options;
220
221 if (targetValue && targetValue.match(new RegExp(match))) {
222 // return the single error
223 return [
224 {
225 message: `Use ${suggestion} instead of ${match}!`,
226 },
227 ];
228 }
229};
230
231const spectral = new Spectral();
232
233spectral.addFunctions({
234 notThat: customNotThatFunction,
235});
236
237spectral.addRules({
238 openapi_not_swagger: {
239 summary: 'Checks for use of Swagger, and suggests OpenAPI.',
240
241 // check every property
242 given: '$..*',
243
244 then: {
245 // reference the function we added!
246 function: 'notThat',
247
248 // pass it the options it needs
249 functionOptions: {
250 match: 'Swagger',
251 suggestion: 'OpenAPI',
252 },
253 },
254 },
255});
256
257// run!
258spectral.run({description: 'Swagger is pretty cool!',}).then(results => {
259 console.log(JSON.stringify(results, null, 4));
260});
261
262// => outputs a single result since we are using the term `Swagger` in our object
263// [
264// {
265// "code": "openapi_not_swagger",
266// "message": "Use OpenAPI instead of Swagger!",
267// "severity": 1,
268// "path": [
269// "description"
270// ]
271// }
272// ]
273```
274
275
276
277## FAQs
278
279**How is this different than [Ajv](https://github.com/epoberezkin/ajv)?**
280
281Ajv is a JSON Schema validator, not a linter. Spectral does expose a `schema` function that you can use in your rules to validate all or part of the target object with JSON Schema (Ajv is used under the hood). However, Spectral also provides a number of other functions and utilities that you can use to build up a linting ruleset to validates things that JSON Schema is not well suited for.
282
283**I want to lint my OpenAPI documents but don't want to implement Spectral right now.**
284
285No problem! A hosted version of Spectral comes **free** with the Stoplight platform. Sign up for a free account [here](https://stoplight.io/?utm_source=github&utm_campaign=spectral).
286
287**What is the difference between Spectral and [Speccy](https://github.com/wework/speccy)?**
288
289With Spectral, lint rules can be applied to _any_ JSON object. Speccy is designed to work with OpenAPI v3 only. The rule structure is different between the two. Spectral uses [JSONPath](http://goessner.net/articles/JsonPath/) `path` parameters instead of the `object` parameters (which are OpenAPI specific). Rules are also more clearly defined (thanks to TypeScript typings) and now require specifying a `type` parameter. Some rule types have been enhanced to be a little more flexible along with being able to create your own rules based on the built-in and custom functions.
290
291## Contributing
292
293If you are interested in contributing to Spectral itself, check out our [contributing docs](CONTRIBUTING.md) to get started.
294
295Also, most of the interesting projects are built _with_ Spectral. Please consider using Spectral in a project or contribute to an [existing one](#example-implementations).
296
297If you are using Spectral in your project and want to be listed in the examples section, we encourage you to open an [issue](https://github.com/stoplightio/spectral/issues).
298
299### Example Implementations
300
301- [Stoplight's Custom Style and Validation Rules](https://docs.stoplight.io/modeling/modeling-with-openapi/style-validation-rules) uses Spectral to validate and lint OpenAPI documents on the Stoplight platform
302- [Spectral GitHub Bot](https://github.com/tbarn/spectral-bot), a GitHub pull request bot that lints your repo's OpenAPI document that uses the [Probot](https://probot.github.io) framework, built by [Taylor Barnett](https://github.com/tbarn)
303- [Spectral GitHub Action](https://github.com/XVincentX/spectral-action), a GitHub Action that lints your repo's OpenAPI document, built by [Vincenzo Chianese](https://github.com/XVincentX/)
304
305## Helpful Links
306
307- [JSONPath Online Evaluator](http://jsonpath.com/), a helpful tool to determine what `path` you want
308- [stoplightio/json](https://github.com/stoplightio/json), a library of useful functions for when working with JSON
309- [stoplightio/yaml](https://github.com/stoplightio/yaml), a library of useful functions for when working with YAML, including parsing YAML into JSON, and a few helper functions such as `getJsonPathForPosition` or `getLocationForJsonPath`
310
311## Thanks :)
312
313- [Phil Sturgeon](https://github.com/philsturgeon) for collaboration and creating Speccy
314- [Mike Ralphson](https://github.com/MikeRalphson) for kicking off the Spectral CLI
315
316## Support
317
318If you have a bug or feature request, please open an issue [here](https://github.com/stoplightio/spectral/issues).
319
320If you need help using Spectral or have a support question, please use the [Stoplight Community forum](https://community.stoplight.io). We've created an open source category for these questions. It's also a great place to share your implementations.
321
322If you want to discuss something in private, you can reach out to Stoplight support at [support@stoplight.io](mailto:support@stoplight.io).