Antonio Gamiz Delgado
Antonio Gamiz Delgado

Reputation: 2113

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

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.

Upvotes: 2

Views: 261

Answers (1)

tom redfern
tom redfern

Reputation: 31800

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_\/{}]*$'

Upvotes: 0

Related Questions