DEV Community

suin
suin

Posted on

How to check if paths are lowercase characters with Spectral

In this post, I show how to use Spectral to check if only lowercase alphanumeric characters are used in the keys of OpenAPI paths.

What is Spectral?

Spectral is a rule-based JSON/YAML linter. It can checks any JSON/YAML, but is especially well designed for OpenAPI.

Problem

To represent paths contains multiple words, there are several forms choices, such as camelCase, kebab-case and underscored:

GET /pullRequests/{id}
GET /pull-requests/{id}
GET /pull_requests/{id}
GET /pullrequests/{id}
Enter fullscreen mode Exit fullscreen mode

When collaborating with a team, the API design conventions should define which format should be selected.

However, people often make mistakes. They may not know the conventions or read them carefully.

Solution: Check the path convention with Spectral

To solve this problem, it is effective to automate the checks with Spectral.

The Spectral rule that checks if paths are all lowercase alphanumeric is like below. Write this in the .spectral.yml.

extends: spectral:oas
rules:
  path-keys-lower-case-alphanumeric:
    message: "Path must be lower case. Only lower case alphanumeric characters are allowed."
    given: "$.paths"
    then:
      field: "@key"
      function: pattern
      functionOptions:
        match: "^(?:\\{[^}]+\\}|[/a-z\\d])*$" # https://regex101.com/r/eHmZ29/1
Enter fullscreen mode Exit fullscreen mode

By adding this rule, Spectral will warn if the path contains uppercase letters or hyphens.

$ npx spectral lint openapi-spec.yaml
/path/to/my/openapi-spec.yaml
 17:15  warning  path-keys-lower-case-alphanumeric  Path must be lower case. Only lower case alphanumeric characters are allowed.  paths./pullRequests
 27:23  warning  path-keys-lower-case-alphanumeric  Path must be lower case. Only lower case alphanumeric characters are allowed.  paths./pull-requests

✖ 2 problems (0 errors, 2 warnings, 0 infos, 0 hints)
Enter fullscreen mode Exit fullscreen mode

Rule details

The rule introduced above uses the Spectral core function pattern. This function checks whether a given field matches a regular expression.

The ^(?:\{[^}]+\}|[/a-z\d])*$ is the regular expression that checks if the paths contains only lower case alphanumeric. This expression matches the following strings:

/
/foo
/123
/foobar
/foo123
/{foo}
/{fooBar}
/{foo_bar}
/{foo-bar}
/users
/users/{userId}
/users/{user-id}
/users/{userid}
/users/{user_id}
Enter fullscreen mode Exit fullscreen mode

On the other hand, the following strings are prohibited:

/Foo
/fooBar
/foo-bar
/foo_bar
/temas/{teamId}/MEMBERS/{userId}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)