instrumenta / openapi2jsonschema

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

nullable does not get converted correctly #24

Open webmaster777 opened 5 years ago

webmaster777 commented 5 years ago

in a swagger 2.0 yaml file:

# some property in a definition
      datumStart:
        type: string
        format: date
        example: '2019-01-13'
        nullable: true

when converted to schema:

Actual output

    "datumStart": {
      "nullable": true, 
      "type": "string", 
      "example": "2019-01-13", 
      "format": "date"
    }, 

Expected output

    "datumStart": {
      "type": ["string", "null"], 
      "example": "2019-01-13", 
      "format": "date"
    }, 
mzsombor commented 4 years ago

Although my use case might be different than yous I still think it could be useful to share my results. I recently started to use swaggerhub (openapi3) for api definition. I was impressed of how useful this tool can be, but when it comes to data validation in python things become tricky. According to https://openapi.tools/ there is no data validation support in python so I started to look for alternatives and this is how I ended up using openapi2jsonschema but ran into the same "nullable not being converted" issue.

After several hours spent on looking for different projects I found https://github.com/p1c2u/openapi-core and an issue regarding data validation in python: https://github.com/p1c2u/openapi-core/issues/154 . Using the example from this issue I managed to write a simple python3 script to validate data against an openapi3 schema.

from jsonschema.validators import RefResolver
from openapi_spec_validator import default_handlers
from openapi_spec_validator.validators import Dereferencer
from openapi_core.schema.schemas.registries import SchemaRegistry

schema1 ={
    "openapi": "3.0.0",
    "info": { "title": "", "version": "0.1" },
    "paths": None,
    "components": {
        "schemas": {
            "test": {
                "type": "string",
                "pattern": "test"
            }
        }
    }
}

schema2 = {
    "$ref": "#/components/schemas/test"
}

resolver = RefResolver.from_schema(schema1, handlers=default_handlers)
dereferencer = Dereferencer(resolver)
schema_registry = SchemaRegistry(dereferencer)
schema, here = schema_registry.get_or_create(schema2)

schema.validate("tes")

I'm not familiar with the libraries that are imported but you can see that jsonschema is still used so you might be able to extract your jsonschema data from there.