How to force snake_case in all request and response parameters in spectral

138 Views Asked by At

I'm trying to use spectral to make all the property names in request and response to match snake_case name convention, but I am not able to get the syntax right. I have the following config file for spectral:

extends: ["spectral:oas", "spectral:asyncapi"]
rules:
  snake-case-for-keys:
    description: Keys must use snake_case
    severity: error
    given: $.schemas.*.properties.*
    then:
      field: '@key'
      function: pattern
      functionOptions:
        match: '^[a-z_\/{}]*$'

What I want is that if you write the following yaml then it fails because someProperty should be written like some_property:

components:
  schemas:
    SomeSchema:
      type: array
      items:
        type: object
        properties:
          someProperty: # should be 'some_property'
          type: string

For now I think checking that on the schemas is enough, but not sure if I should check it also on all the responses and requests too. Any idea how to achieve this behaviour? I suppose I have a wrong given clause in my rule.

1

There are 1 best solutions below

0
On

You should indeed change your given clause, so that it resolves to property definitions which happen to be inline OR defined under components/schemas section.

To do this, use the following jsonpath-plus path

given: $..properties[*]~

This path resolves to any schema property anywhere in the document.

Additionally, you shouldn't need the field: '@key' statement as spectral will iterate all the returned "given" values.

So in conclusion, try the following rule definition:

rules:
  snake-case-for-keys:
    ...
    given: $..properties[*]~
    then:
      function: pattern
      functionOptions:
        match: '^[a-z_\/{}]*$'