stoplightio / spectral-documentation

Teach Spectral how to help improve the quality of your OpenAPI-based documentation.
8 stars 4 forks source link

OAS Objects that should have Schema or Examples #1

Closed philsturgeon closed 1 year ago

philsturgeon commented 1 year ago

Seeing as examples can be defined in various OAS objects, or in the schema keyword of that object, things get preeeeetty confusing pretty quickly and we could have people defining the example in the schema only to be shouted at about how it needs to be in the Example too making things potentially redundant.

For now I am thinking we get people to define a schema or example(s), so that at least Elements has something to work with.

  1. Parameters should have Parameter Examples or a Schema
  OAS2
    given: $.paths[*][*]..parameters[(type !== body)]

    one of:
    - x-example: apple
    - example: apple (some people did this anyway)
    - default 
    - enum 
    - format

  OAS3
    given: $.paths[*][*]..parameters[*]

    one of:
    - example
    - examples
    - schema
  1. Request/Response should have Media Type Examples or Schema
  OAS2
    given: 
    - $.paths[*][*]..parameters[(type == body)]
    - $.paths[*][*].responses[*]

    one of 
    - schema
    - examples

  OAS3
    given: 
    - $.paths[*][*].requestBody.content[*]
    - $.paths[*][*].responses[*].content[*]

    one of:
      schema
      example
      examples

If we take this approach, what should be enforced for schema objects? The original thought was "make sure they've got one of example, examples, default, enum, etc. but doing that could enforce both schema.example and an example next to schema.

The rule is already written and easy enough, but doesn't check sub schemas.

   'docs-parameter-example': {
      message: "Parameters SHOULD contain examples.",
      description: "Documentation tools use examples to provide more realistic representations of wht is contained in the parameter, so users can send valid requests sooner.",
      severity: DiagnosticSeverity.Warning,
      given: "$..parameters[*].schema",
      formats: [oas3],
      then: {
        function: schema,
        functionOptions: {
          schema: {
            oneOf: [
              { required: ['examples'] },
              { required: ['example'] },
              { required: ['default'] },
              { required: ['enum'] },
              { required: ['const'] },
            ]
          }
        }
      }
    },

Givens for checking there is an example at the top of a schema or enough examples in sub schemas get pretty wild:

"$.paths[*][*]..content[*].schema..*[?(@property !== 'properties' && @property === 'type' && @ && (@.items === void 0 || @.properties === void 0 ))]^",
philsturgeon commented 1 year ago

Done, currently writing tests.