instrumenta / openapi2jsonschema

Convert OpenAPI definitions into JSON schemas for all types in the API
Other
226 stars 87 forks source link

KeyError when a definition doesn't have "properties" #49

Open mengqiy opened 3 years ago

mengqiy commented 3 years ago

https://github.com/instrumenta/openapi2jsonschema/blob/d697cbff8a25f520e125e3a5f79cb4e9b972e8ce/openapi2jsonschema/command.py#L99 will cause KeyError when there is no "properties" in some schema (CRDs and some new built-in types in OSS k8s).

For examples:

  "io.gke.nodemanagement.v1alpha1.UpdateInfo": {
      "type": "object",
      "x-kubernetes-group-version-kind": [
        {
          "group": "nodemanagement.gke.io",
          "kind": "UpdateInfo",
          "version": "v1alpha1"
        }
      ]
    },
garethahealy commented 3 years ago

Am seeing the same error:

Traceback (most recent call last):
  File "/Users/garethhealy/.pyenv/versions/3.8.2/bin/openapi2jsonschema", line 10, in <module>
    sys.exit(default())
  File "/Users/garethhealy/.pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/Users/garethhealy/.pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/Users/garethhealy/.pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/garethhealy/.pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/garethhealy/.pyenv/versions/3.8.2/lib/python3.8/site-packages/openapi2jsonschema/command.py", line 99, in default
    if expanded and "apiVersion" in type_def["properties"]:
KeyError: 'properties'

any workaround?

piotrminkina commented 3 years ago

Try below command for workaround, but first You must install jq. In this example I fetch OpenAPI directly from Kubernetes API, so if You want parse contents from file instead of URL then replace curl with cat. This command should work fine in BASH or ZSH, but not SH.

openapi2jsonschema \
    --output output_dir \
    --kubernetes \
    --stand-alone \
    --strict \
    file://<(curl -sSL http://localhost:8001/openapi/v2 | jq '.definitions[] |= if .["x-kubernetes-group-version-kind"] then . + {properties: (.properties // {})} else . end')