s-knibbs / dataclasses-jsonschema

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

Allow to use fields for arbitrary schema extensions. #121

Closed mic47 closed 2 years ago

mic47 commented 4 years ago

What does it do

This adds "schema" into FieldMeta, that is used to add arbitrary updates to schema (similar to extensions, but not adding x-). Alternate option was to make extensions to work without "x-" if it is not swagger, but that didn't look backward compatible.

Why

https://github.com/s-knibbs/dataclasses-jsonschema/issues/120

Currently, you can use field metadata for custom descriptions, examples. But to do more custom validation (like constraints for integers), you have to use NewType and registering this type. While NewType is good for things like Email, and Enum-like things, it's cumbersome for numeric things, since you have to create newtype for each restriction (i.e. for restricting by 1 and 0 you need separate types). Instead, metadata from field could be used, as like this:

@dataclass
class Box(JsonSchemaMixin):
    """A box."""
    width: int = field(metadata={
        "description": "Some description", 
        "schema": {"minimum": 1}
    })
mic47 commented 4 years ago

@s-knibbs: I know you are probably busy, but any chance you would find time to review this?