Saltar al contenido

Using Spectral to remove fluff from your OpenAPI definition

Using Spectral to remove fluff from your OpenAPI definition

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 fluff.

Generally, a linter is a tool that scans source code for errors, errors, style issues, and redundant code. Regarding the API, can be applied down tools to check for errors in the API design process. Linting can ensure that the API is not only technically perfect, but also meets standard API guidelines.

With the appearance OpenAPI As a standard API specification, developers using OpenAPI must ensure that their API definitions meet the specifications. Then, we will explain how to filter your OpenAPI YAML or JSON definitions using an open source tool called Spectral.

First of all, why is clothing important?

  • Code standardization : Linting helps you follow standard coding guidelines. Code standardization can reduce clutter, help others understand it, and ultimately save time.
  • Security issues – The standards usually comply with specific security measures. Therefore, passing your code through a linter could help reduce gaps or vulnerabilities.
  • Improving performance – If developers do not meet a standard, the code base can easily become much larger, resulting in poor code and performance issues. Linting can help increase performance and ensure high quality code.
  • Look for errors : Suppose you wrote a hundred lines of code, but it doesn’t run. Linting helps identify code errors in real time, ensuring high quality error-free code.
  • Time saving : all the points mentioned above lead us to the maximum benefit: saving time. Coating can reduce washing time, resulting in time savings.

What is spectral?

Spectral is an OpenAPI specification coverage tool developed by Spotlight. It is an open source tool available on Github with over 700 stars at the time of writing.

Similar to Robocop and Eslint, Spectral is a terminal-based linter, which means it does not have a user interface. With Spectral, developers can filter OpenAPI v2 and v3 definitions and create automated style guides.

Now, let’s try running Spectral for lint:


Step 1: Install Spectral

Assuming you already have Node.js installed, open the terminal and create a folder named scame-apifrom the following command:

mkdir lint-api
cd lint-api

Now, let’s install Spectral. To do this, use the following command:

Copy to clipboardnpm install -g @stoplight/spectral

To validate the installation, check the Spectral version. Use the following command to verify the version:

Copy to clipboardspectral 

Step 2: Create an OpenAPI 3.1 specification

Now create a file with the name test.yamland paste the following code:

Copy to clipboardopenapi: 3.0.1
  title: Employees API Spec
  description: Working with employee details
  version: v1
- url: http://localhost:8080/employees
  description: The employee api
- name: employee details api spec
    summary: Employees
    description: API to work with employee details
      - employees
      summary: Get list of employees
      description: Retrieve the list of employees and their details
      operationId: getEmployees
          description: request to get list of employees
                $ref: '#/components/schemas/EmployeeResponse'

Code explanation:

This is an example of an OpenAPI YAML specification that describes an API for employee information.

Step 4: Specify a set of rules for the specification

Now create a file named rule.spectral.yamland paste the following sets of rules:

Copy to clipboardrules:
    description: "OpenAPI `servers` must be present and non-empty."
    formats: ["oas3"]
    given: "$"
      field: servers
      function: schema
            type: object
          minItems: 1
          type: array

Code explanation:

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

Step 5: Connect the API

Now that you’ve defined an API and rule sets, it’s time to leave the API. In your terminal, paste the following code to run the liner:

Copy to clipboardspectral lint test.yaml

You should see the following output:

Copy to clipboard10: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.$ref

2 problems (2 errors, 0 warnings, 0 infos, 0 hints)

This answer means that something is wrong with the API specification. Let’s try to correct this problem. To solve Labels must have a descriptionerror, we just need to delete the first one Tags.

Now, let’s try running the liner again:

Copy to clipboardspectral lint test.yaml

You should see the following output:

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

This problem persists because the scheme in Employee responsereality does not exist. So we can eliminate this one too. To do this, remove the line that writes $ ref: ‘# / components / schemas / EmployeeResponse’from the file test.yaml.

Let’s try running the liner again:

Copy to clipboardspectral lint test.yaml

And boom! No errors found!

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

Note that Spectral also automatically detected the version of the OpenAPI specification.

The last words

With a tool like Spectral, connecting an API definition becomes a breeze. But the fun doesn’t end there: you can also use Spectral to polish non-OpenAPI definitions, including AsyncAPI. You can also create custom rule sets, allowing you to define new rules and even disable pre-existing rules. This flexibility means that using Spectral to define APIs has many advantages.