s-knibbs / dataclasses-jsonschema

JSON schema generation from dataclasses
MIT License
165 stars 38 forks source link

Unresolvable JSON pointer in nested definition #146

Open juliuszsielski opened 3 years ago

juliuszsielski commented 3 years ago

Hi,

I am trying to convert dataclass to JSON Schema to be able to use api.model() in flask-restx app. I have a problem with nested objects.

@dataclass
class A(JsonSchemaMixin):
    text: str
    number: int

@dataclass
class B(JsonSchemaMixin):
    test: A

test_model = api.schema_model('B', B.json_schema())

When I try to send:

{
"test": {
          "text": "test",
          "number": 1
         }
}

It gives me an error jsonschema.exceptions.RefResolutionError: Unresolvable JSON pointer: 'definitions/A' // Werkzeug Debugger

It works when I send something different than object containing "test", but not for nested object. How can I make it work?

juliuszsielski commented 3 years ago

I partially solve my problem using this solution

import jsonref
import copy 
from dataclasses_jsonschema import JsonSchemaMixin
from dataclasses import dataclass
from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class A(JsonSchemaMixin):
    text: str
    number: int

@dataclass_json
@dataclass
class B(JsonSchemaMixin):
    test: A

jsonref_schema = jsonref.loads(json.dumps(B.json_schema()))
test_model = api.schema_model('Test model', copy.deepcopy(jsonref_schema))

The problem is when I try to change class B to:

class B(JsonSchemaMixin):
    test: A = A()

Then I gets error:

def encoder(_, v, o): return v.to_dict(omit_none=o, validate=False)
TypeError: to_dict() got an unexpected keyword argument 'omit_none'
s-knibbs commented 3 years ago

I'd need a more complete repro to understand what the issue is here. I don't really know what api.schema_model is doing.

juliuszsielski commented 3 years ago

I am using Flask restx library for hosting my rest api app. There is a possibility to use dataclass schema for validation. Here you can find documentation. api.schema_model is used for validation purpose and creating model for swagger UI. You can find simple restx app that I created here. Then by running python app.py you get the access to local host where rest api and swagger UI is running. The problem is that not every dataclass definiton are valid for JsonSchemaMixin.