Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for metadata on custom fields. #21

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion marshmallow_jsonschema/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def get_properties(self, obj):

for field_name, field in sorted(obj.fields.items()):
if hasattr(field, '_jsonschema_type_mapping'):
schema = field._jsonschema_type_mapping()
schema = self.__class__._from_custom_field_type(field)
elif field.__class__ in mapping:
pytype = mapping[field.__class__]
schema = self.__class__._from_python_type(field, pytype)
Expand Down Expand Up @@ -166,3 +166,20 @@ def _from_nested_schema(cls, field):
}

return schema

@classmethod
def _from_custom_field_type(cls, field):
json_schema = field._jsonschema_type_mapping()

if field.default is not missing:
json_schema['default'] = field.default

if field.metadata.get('metadata', {}).get('description'):
json_schema['description'] = (
field.metadata['metadata'].get('description')
)

if field.metadata.get('metadata', {}).get('title'):
json_schema['title'] = field.metadata['metadata'].get('title')

return json_schema
13 changes: 11 additions & 2 deletions tests/test_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,18 @@ def _serialize(self, value, attr, obj):

class UserSchema(Schema):
name = fields.String(required=True)
favourite_colour = Colour()
favourite_colour = Colour(default='#ffffff',
metadata=dict(
description="User's favorite colour",
title="Colour")
)

schema = UserSchema()
json_schema = JSONSchema()
dumped = json_schema.dump(schema).data
assert dumped['properties']['favourite_colour'] == {'type': 'string'}
assert dumped['properties']['favourite_colour'] == {
'type': 'string',
'default': '#ffffff',
'description': "User's favorite colour",
'title': "Colour",
}