Spectral rule to check errors and query parameters are defined

I am currently using stoplight studio to define a number of APIs.
I am aware that you can write custom rules that spectral will then apply against each of the APIs.
I am looking for some advice and/or examples on how to implement two separate custom rules that will:

  1. ensure that every endpoint contains a definition for a 422 response with an error response defined as a common model

  2. ensure that every endpoint contains an optional query parameter

Thanks in advance for your help
David

Hey David.

A rule checking whether every endpoint has an optional query parameter could look as follows

{
  "rules": {
    "optional-request-query-parameter": {
      "message": "Query request parameter must be optional",
      "severity": "error",
      "given": "$.paths.*.*.parameters.[?(@.in === \"query\")]",
      "then": {
        "field": "required",
        "function": "enumeration",
        "functionOptions": {
          "values": ["false"]
        }
      }
    }
  }
}

Regarding the first question - do you mean a model from common shared library or just a standalone model?

Jakub

hi Jakub,

Thanks for your reply. Yes, I do mean referencing a model from the common/shared set within stoplight studio rather than a model that is defined locally to the API endpoint.

Thanks
David

Hi Jakub,

I have tried to convert the JSON example you provided me with into YAML, the definition doesn’t appear to be reporting any errors with the format of the spectral.yaml file within stoplight studio, but it does not appear to be working as I expected.

I am trying to achieve the following rule:

If the endpoint does not contain an optional query parameter called society then report an error.

This is the configuration I currently have within the spectral.yaml file

extends: 'spectral:oas3'
rules:
  oa3-schema: true
  operation-summary-formatted: warn
  
  society-must-be-an-optional-query-parameter:
description: Ensures that the service contains society as an optional query parameter
recommended: true
severity: error
message: The service must contain society as an optional query parameter
given: "$.paths.*.*.parameters.[?(@.in === \"query\")]"
then:
  field: 'society'
  function: enumeration
  functionOptions:
    "values": ["false"]

Can you or anyone else help?

Thanks in advance for your help

David