Using Custom Validations
Behind the Stoplight API design interface is Spectral, Stoplight’s open source validation engine. Spectral was built from the ground up to be fast, easy-to-use, and, most importantly, extensible. This article discusses how to customize the rules that power Spectral for your own purposes, including how to create your own rules.
Accessing Your Project’s Git Repository
Before you can update the validation rules for a Stoplight project, you will
first need to clone your project repository using
git. Once cloned, you should see a
lint.yml file within the repository
$ ls -l total 64 -rw-r--r-- 1 user user 821 Jun 26 10:49 lint.yml [...]
Modifying the Validation Configuration
lint.yml configuration file is what the API design interface uses for
determining what rules to apply to the specifications within a project.
The lint configuration has a root object
rules, with two possible formats to
apply the rules to:
oas2 (for OpenAPI v2) and
oas3 (for OpenAPI v3). For
example, to set a custom OpenAPIv2 rule you would start with:
rules: oas2: my-custom-rule: [...]
my-custom-rule is the key for the new rule, which will contain the
contents of the rule. The contents of the rule object can vary depending on the rule’s
As a simple example, let’s say we want to ensure that a special spec extension
x-partner-segment is present in all of our OpenAPI v2 APIs. To enforce this,
we’ll create a
truthy function rule, which ensures that a value is present and
is equal to a non-empty string. This is what our rule would look like:
rules: oas2: contains-partner-extension: enabled: true summary: The API has a `x-partner-segment` extension set. type: "style" given: "$" then: field: x-partner-segment function: truthy
enableddictates whether the rule is enabled by default. By setting it to
true, it will be enabled on project load.
summaryis the summary of the rule that will display in the Stoplight user interface when the rule is violated.
typecan be equal to either
givenis the JSONpath to the elements in the API specification that we want to operate on. The
$equals the root of the object, which is where we want our extension to be set
thenis the function definition itself, which takes a
truthyfunction then takes a
fieldparameter, which is what we want to evaluate as “truthy” or not (
x-partner-segment). Different functions take different parameters, so be sure to check the latest Spectral documentation for the latest function parameters.