API developers have a lot to focus on, including security, data, response time, code optimization, and many other areas. But one of the most underrated aspects of quality API design is linting.

In general terms, a linter is a tool that analyzes source code to discover errors, bugs, styling issues, and redundant code. In API terms, linting tools can be applied to check for errors within the API design process. Linting can ensure the API is not only technically perfect but also complies with standard API guidelines.

With the rise of OpenAPI as a standard API specification, developers using OpenAPI must ensure their API definitions follow the specification. Below, we’ll walk through how to lint your OpenAPI YAML or JSON definitions using an open-source tool called Spectral.

First, Why Is Linting Important?

  • Code Standardization: Linting helps you follow standard coding guidelines. Standardizing code can reduce clutter, help others understand it, and ultimately save time.
  • Security Issues: Standards usually follow specific security measures. Thus, passing your code through a linter could help reduce loopholes or vulnerabilities.
  • Performance Improvement: If developers do not follow a standard, the codebase can easily become much larger, which results in performance issues and poor-quality code. Linting can help increase performance and ensure high-quality code.
  • Find Errors: Imagine you wrote a hundred lines of code, but it fails to run. Linting helps identify code errors in real-time, ensuring higher quality, error-free code.
  • Time-Saving: All the points mentioned above lead us to the ultimate benefit — time-saving. Linting can reduce debugging time which will result in saved time.

What is Spectral?

Spectral is an OpenAPI specification linting tool developed by Spotlight. It is a completely open-source tool available on Github with about 700+ stars at the time of writing.

Similar to Robocop and eslint, Spectral is a terminal-based linter, meaning it doesn’t have a UI to work with. Using Spectral, developers can lint OpenAPI v2 and v3 definitions and create automated style guides.

Now, let’s try to run Spectral to lint:

Prerequisites

  • Node.js

Step 1: Installing Spectral

Assuming that you already have Node.js installed, open the terminal and create a folder named lint-api using the below command:

mkdir lint-api
cd lint-api

Now, let’s install Spectral. To do so, use the below command:

npm install -g @stoplight/spectral

To validate the installation, let’s check out the version of Spectral. Use the below command to check the version:

spectral --version

Step 2: Creating an OpenAPI 3.1 Specification

Now, create a file named test.yaml and paste the below code:

openapi: 3.0.1
info:
  title: Employees API Spec
  description: Working with employee details
  version: v1
servers:
- url: http://localhost:8080/employees
  description: The employee api
tags:
- name: employee details api spec
paths:
  /api/v1/employees:
    summary: Employees
    description: API to work with employee details
    get:
      tags:
      - employees
      summary: Get list of employees
      description: Retrieve the list of employees and their details
      operationId: getEmployees
      responses:
        "200":
          description: request to get list of employees
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EmployeeResponse'

Code Explanation:

This is a sample OpenAPI YAML specification that describes an API for employee information.

Step 4: Specifying a Rule Set for the Specification

Now, create a file named rule.spectral.yaml and paste the below rule sets:

rules:
  oas3-api-servers:
    description: "OpenAPI `servers` must be present and non-empty."
    formats: ["oas3"]
    given: "$"
    then:
      field: servers
      function: schema
      functionOptions:
        schema:
          items:
            type: object
          minItems: 1
          type: array

Code Explanation:

These rules define the format of the API, i.e., oas3, which is used for OpenAPI v3. It also defines the type and schema of the API.

Step 5: Linting the API

Now that you have defined an API and rule sets, it’s time to lint the API. On your terminal, paste the below code to run the linter:

spectral lint test.yaml

You should see the below output:

10:3  error  my-rule-one  Tags must have a description.                           tags[0]
 27:23  error  invalid-ref  '#/components/schemas/EmployeeResponse' does not exist  paths./api/v1/employees.get.responses[200].content.application/json.schema.$ref2 problems (2 errors, 0 warnings, 0 infos, 0 hints)

This response means that something is wrong with the API specification. Let’s try to correct this issue. To resolve the Tags must have a description error, we just need to remove the first tags.

Now let’s try to rerun the linter:

spectral lint test.yaml

You should see the following output:

28:23  error  invalid-ref  '#/components/schemas/EmployeeResponse' does not exist  paths./api/v1/employees.get.responses[200].content.application/json.schema.$ref1 problem (1 error, 0 warnings, 0 infos, 0 hints)

This problem persists since the schema EmployeeResponse actually doesn’t exist. So we can remove that one also. To do so, remove the line that says $ref: '#/components/schemas/EmployeeResponse' from the file test.yaml.

Let’s try to rerun the linter:

spectral lint test.yaml

And boom! No errors found!

OpenAPI 3.x detected
No results with a severity of 'error' or higher found!

Note that Spectral has also detected the OpenAPI Specification version automatically.

Final Words

With a tool like Spectral, linting an API definition becomes very straightforward. But the fun doesn’t end there — you can also use Spectral to lint non-OpenAPI definitions, including AsyncAPI. You can also create custom rule sets, allowing you to define new rules and even disable pre-existing rules too. This flexibility means using Spectral for API definition linting comes with many advantages.