Convert Figma logo to code with AI

stoplightio logospectral

A flexible JSON/YAML linter for creating automated style guides, with baked in support for OpenAPI v3.1, v3.0, and v2.0 as well as AsyncAPI v2.x.

2,448
235
2,448
170

Top Related Projects

The OpenAPI Specification Repository

Swagger Editor

23,260

📘 OpenAPI/Swagger-generated API Reference Documentation

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

9,725

RESTful web API Documentation Generator.

Quick Overview

Spectral is an open-source JSON/YAML linter and validator, primarily used for OpenAPI and AsyncAPI specifications. It allows users to create custom rulesets to enforce style guidelines and best practices in API descriptions, ensuring consistency and quality across API documentation.

Pros

  • Highly customizable with support for custom rulesets and functions
  • Integrates well with various development workflows and CI/CD pipelines
  • Supports multiple specification formats (OpenAPI, AsyncAPI, JSON Schema)
  • Provides a CLI tool and JavaScript API for flexible usage

Cons

  • Learning curve for creating complex custom rules
  • Limited built-in rules compared to some other linting tools
  • Performance can be slower for very large specifications
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Basic usage with CLI:
spectral lint openapi.yaml

This command lints an OpenAPI specification file using the default ruleset.

  1. Using a custom ruleset:
import { Spectral, Document } from '@stoplight/spectral-core';
import { bundleAndLoadRuleset } from '@stoplight/spectral-ruleset-bundler/with-loader';

const spectral = new Spectral();
const ruleset = await bundleAndLoadRuleset('./custom-ruleset.yaml');
spectral.setRuleset(ruleset);

const document = new Document('{"openapi": "3.0.0", ...}', 'openapi.json');
const results = await spectral.run(document);
console.log(results);

This example demonstrates how to use a custom ruleset with the JavaScript API.

  1. Creating a custom rule:
module.exports = {
  rules: {
    'operation-description': {
      description: 'Operation must have a description.',
      given: '$.paths[*][get,post,put,delete,options,head,patch,trace]',
      then: {
        field: 'description',
        function: 'truthy',
      },
    },
  },
};

This code defines a custom rule that checks if all API operations have a description.

Getting Started

To get started with Spectral:

  1. Install Spectral globally:

    npm install -g @stoplight/spectral-cli
    
  2. Create a basic ruleset file (e.g., .spectral.yaml):

    extends: spectral:oas
    rules:
      operation-description: error
    
  3. Lint your OpenAPI specification:

    spectral lint openapi.yaml
    

For more advanced usage, refer to the official Spectral documentation.

Competitor Comparisons

The OpenAPI Specification Repository

Pros of OpenAPI-Specification

  • Widely adopted industry standard for API documentation
  • Comprehensive specification covering all aspects of API design
  • Extensive ecosystem of tools and libraries supporting the standard

Cons of OpenAPI-Specification

  • Can be complex and verbose for simple APIs
  • Requires manual creation and maintenance of specification files
  • Limited built-in validation capabilities

Code Comparison

OpenAPI-Specification example:

openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
paths:
  /users:
    get:
      summary: List users
      responses:
        '200':
          description: Successful response

Spectral example (rule definition):

rules:
  operation-description:
    description: Operation should have a description.
    given: $.paths.*[get,post,put,delete,patch]
    then:
      field: description
      function: truthy

Key Differences

  • OpenAPI-Specification focuses on API description and documentation
  • Spectral is a linter and validator for API descriptions, including OpenAPI
  • OpenAPI-Specification provides a structure for API definitions
  • Spectral offers customizable rules for validating API specifications

Both projects complement each other, with Spectral often used to validate OpenAPI specifications.

Swagger Editor

Pros of Swagger Editor

  • Provides a full-featured web-based editor for OpenAPI specifications
  • Offers real-time preview and documentation generation
  • Includes built-in validation and error highlighting

Cons of Swagger Editor

  • Limited customization options for linting rules
  • Primarily focused on editing and less on advanced validation scenarios
  • Requires a web browser to run, which may not be suitable for all workflows

Code Comparison

Spectral (JSON configuration):

{
  "extends": ["spectral:oas", "spectral:asyncapi"],
  "rules": {
    "operation-description": "warn",
    "no-$ref-siblings": "off"
  }
}

Swagger Editor (YAML configuration):

swagger: '2.0'
info:
  version: 1.0.0
  title: Sample API
paths:
  /users:
    get:
      summary: List users

Key Differences

  • Spectral is a standalone linter that can be integrated into various workflows, while Swagger Editor is a comprehensive web-based editor
  • Spectral offers more flexibility in creating custom rulesets and extending existing ones
  • Swagger Editor provides a more user-friendly interface for editing OpenAPI specifications, especially for those new to API design
  • Spectral can be used in CI/CD pipelines and command-line interfaces, making it more versatile for automation
23,260

📘 OpenAPI/Swagger-generated API Reference Documentation

Pros of Redoc

  • Generates beautiful, interactive API documentation
  • Supports OpenAPI (Swagger) 2.0 and 3.0 specifications
  • Easy to integrate into existing web applications

Cons of Redoc

  • Focused solely on documentation rendering, not linting or validation
  • Less customizable than some alternatives
  • May require additional tools for a complete API development workflow

Code Comparison

Redoc usage:

<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
<redoc spec-url="https://api.example.com/openapi.json"></redoc>

Spectral usage:

const { Spectral } = require('@stoplight/spectral-core');
const spectral = new Spectral();
spectral.run({ target: './openapi.yaml' });

Key Differences

  • Spectral is primarily a linter and validator for API descriptions
  • Redoc focuses on rendering API documentation
  • Spectral offers more flexibility for custom rulesets and validation
  • Redoc provides a more polished out-of-the-box documentation experience

Both tools serve different purposes in the API development lifecycle. Spectral is ideal for ensuring API description quality, while Redoc excels at presenting API documentation to end-users.

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

Pros of openapi-generator

  • Generates client libraries, server stubs, and documentation for multiple programming languages
  • Supports a wide range of OpenAPI/Swagger versions and formats
  • Offers extensive customization options for generated code

Cons of openapi-generator

  • Steeper learning curve due to its comprehensive feature set
  • May generate unnecessary code for simpler API projects
  • Requires more setup and configuration compared to Spectral

Code Comparison

openapi-generator (Java client generation):

java -jar openapi-generator-cli.jar generate \
  -i petstore.yaml \
  -g java \
  -o /tmp/java-client

Spectral (API linting):

spectral lint petstore.yaml

Key Differences

Spectral focuses on API linting and validation, while openapi-generator is primarily used for code generation across multiple languages. Spectral is more lightweight and easier to integrate into CI/CD pipelines for API quality checks, whereas openapi-generator offers a comprehensive solution for generating API-related code and documentation.

Spectral is ideal for teams looking to enforce API design standards and catch issues early in the development process. openapi-generator is better suited for projects requiring client libraries or server stubs in various programming languages, especially when working with complex APIs that need extensive code generation.

9,725

RESTful web API Documentation Generator.

Pros of apidoc

  • Generates API documentation from inline code comments, making it easier to keep documentation in sync with code
  • Supports multiple programming languages, including JavaScript, Python, and Ruby
  • Offers a simple and straightforward approach to API documentation

Cons of apidoc

  • Limited to generating static HTML documentation, lacking interactive features
  • Requires specific comment syntax, which may not align with existing code documentation practices
  • Less flexible in terms of customization compared to more modern API documentation tools

Code Comparison

apidoc example:

/**
 * @api {get} /user/:id Request User information
 * @apiName GetUser
 * @apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 */

Spectral example (YAML configuration):

rules:
  operation-description:
    description: Operation must have a description.
    given: $.paths.*[get,post,put,delete,patch]
    then:
      field: description
      function: truthy

While apidoc focuses on generating documentation from code comments, Spectral is primarily used for linting and validating API descriptions. Spectral offers more flexibility in terms of rule customization and can be integrated into CI/CD pipelines for automated API contract validation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Demo of Spectral linting an OpenAPI document from the CLI CircleCI npm Downloads Stoplight Forest

  • Custom Rulesets: Create custom rules to lint JSON or YAML objects
  • Ready-to-use Rulesets: Validate and lint OpenAPI v2 & v3.x and AsyncAPI Documents
  • API Style Guides: Automated API Style Guides using rulesets improve consistency across all your APIs
  • Ready-to-use Functions: Built-in set of functions to help create custom rules. Functions include pattern checks, parameter checks, alphabetical ordering, a specified number of characters, provided keys are present in an object, etc.
  • Custom Functions: Create custom functions for advanced use cases

Overview

🧰 Installation

The easiest way to install spectral is to use either npm:

npm install -g @stoplight/spectral-cli

Or yarn:

yarn global add @stoplight/spectral-cli

There are also additional installation options.

💻 Usage

1. Create a local ruleset

Spectral, being a generic YAML/JSON linter, needs a ruleset to lint files. A ruleset is a JSON, YAML, or JavaScript/TypeScript file (often the file is called .spectral.yaml for a YAML ruleset) that contains a collection of rules, which can be used to lint other JSON or YAML files such as an API description.

To get started, run this command in your terminal to create a .spectral.yaml file that uses the Spectral predefined rulesets based on OpenAPI or AsyncAPI:

echo 'extends: ["spectral:oas", "spectral:asyncapi"]' > .spectral.yaml

If you would like to create your own rules, check out the Custom Rulesets page.

2. Lint

Use this command if you have a ruleset file in the same directory as the documents you are linting:

spectral lint myapifile.yaml

Use this command to lint with a custom ruleset, or one that's located in a different directory than the documents being linted:

spectral lint myapifile.yaml --ruleset myruleset.yaml

📖 Documentation

Once you've had a look through the getting started material, some of these guides can help you become a power user.

  • Different Workflows - When and where should you use Spectral? Editors, Git hooks, continuous integration, GitHub Actions, wherever you like!
  • Using the command-line interface - Quickest way to get going with Spectral is in the CLI.
  • Using the JavaScript API - Access the raw power of Spectral via the JS, or hey, TypeScript if you want.
  • Custom Rulesets - Need something more than the core rulesets provide? Fancy building your own API Style Guide? Learn how to create a custom ruleset.
  • Custom Functions - Handle more advanced rules, by writing a little JavaScript/TypeScript and calling it as a function.

ℹ️ Support

If you need help using Spectral or have any questions, you can use GitHub Discussions, or visit the Stoplight Community Discord. These communities are a great place to share your rulesets, or show off tools that use Spectral.

If you have a bug or feature request, create an issue for it.

🌎 Real-World Rulesets

Stoplight has a set of Spectral rulesets that were created to help users get started with Stoplight's Style Guides. You can find them on API Stylebook, and you can download the source Spectral file by selecting a style guide on the project sidebar and selecting Export -> Spectral File(s) on the top-right. A few noteworthy style guides are:

  • OWASP Top 10 - Set of rules to enforce OWASP security guidelines.
  • URL Style Guidelines - Set of rules to help developers make better and consistent endpoints.
  • Documentation - Scan an OpenAPI description to make sure you're leveraging enough of its features to help documentation tools like Stoplight Elements, ReDoc, and Swagger UI build the best quality API Reference Documentation possible.

There are also rulesets created by many companies to improve their APIs. You can use these as is to lint your OpenAPI descriptions, or use these as a reference to learn more about what rules you would want in your own ruleset:

  • Adidas - Adidas were one of the first companies to release their API Style Guide in a written guide and a Spectral ruleset. Lots of good rules to try in here.
  • APIs You Won't Hate - An opinionated collection of rules based on advice in the APIs You Won't Hate community.
  • Azure - Ruleset and complimentary style guide for creating OpenAPI 2 or 3 definitions of Azure services.
  • Box - Lots of Custom Functions being used to enforce good practices that the Box API governance folks are interested in.
  • DigitalOcean - Keeping their OpenAPI nice and tidy, enforcing use of $ref (probably to minimize conflicts), naming conventions for Operation IDs, and all sorts of other handy OpenAPI tips.
  • Tranascom - Don't even think about using anything other than application/json.
  • Zalando - Based on Zalando's RESTFUL API Guidelines, covers a wide-range of API topics such as versioning standards, property naming standards, the default format for request/response properties, and more.

Check out some additional style guides here:

⚙️ Integrations

🏁 Help Others Utilize Spectral

If you're using Spectral for an interesting use case, contact Stoplight for a case study. 🎉

👏 Contributing

If you are interested in contributing to Spectral, check out CONTRIBUTING.md.

🎉 Thanks

📜 License

Spectral is 100% free and open-source, under Apache License 2.0.

🌲 Sponsor Spectral by Planting a Tree

If you would like to thank Stoplight for creating Spectral, buy the world a tree.

NPM DownloadsLast 30 Days