kin-openapi icon indicating copy to clipboard operation
kin-openapi copied to clipboard

How to catch invalid OpenAPI v3 spec

Open JeanChristopheMorinPerso opened this issue 2 years ago • 2 comments

Hello! I'm trying to find how I can make this library to return an error when loading an invalid spec.

Basically, I have an invalid v3 spec that looks like this:

openapi: "3.0.3"
info:
  title: 'My app'
  version: 1.0.0
  description: 'An API'

paths:
  /v1/operation:
    delete:
      summary: Delete something
      responses:
        200:
          description: Success
        default:
          description: '* **400** - Bad Request'
          # Notice here schema is invalid. It should instead be:
          # content:
          #   application/json:
          #     schema:
          #       $ref: '#/components/schemas/Error'
          schema:
            $ref: '#/components/schemas/Error'
components:
  schemas:
    Error:
      type: object
      description: An error response body.
      properties:
        message:
          description: A detailed message describing the error.
          type: string

I load that spec using the openapi3.Loader:

loader := openapi3.NewLoader()
loader.IsExternalRefsAllowed = true

schema, err := loader.LoadFromFile("/path/to/spec.yaml")
if err != nil {
	fmt.Println("Failed to load swagger_template.yaml:", err.Error())
	os.Exit(1)
}

// Not used in my current example but that's what my code does
schema.InternalizeRefs(context.Background(), nil)

err = schema.Validate(context.Background())
if err != nil {
	fmt.Println("Validation failed:", err.Error())
}

I would expect that either LoadFromFile or Validate return an error saying that it's not a valid spec or something, but it's not.

Is there a way to tell the library to return an error in such cases?

Thanks!

You could use something like this: https://github.com/xeipuuv/gojsonschema#meta-schema-validation

You can use any jsonschema validator to validate the openapi specs you have against the official openapi schema ...

timo-klarshift avatar May 10 '22 19:05 timo-klarshift

Agree that it would be nice if this library would use jsonschema to validate against the spec rather than requiring the user to do so

chris-smith-zocdoc avatar May 24 '22 17:05 chris-smith-zocdoc

Thanks @fenollp !