hfaran / Tornado-JSON

A simple JSON API framework based on Tornado
http://tornado-json.readthedocs.org/
MIT License
273 stars 60 forks source link

Use default values for missing properties. #71

Closed normanjaeckel closed 8 years ago

normanjaeckel commented 9 years ago

It would be nice if the package could add default values for missing properties to the body if mentioned in the schema. Untested Example:

@schema.validate(
    input_schema={
        "type": "object",
        "properties": {
            "foo": {
                "type": "integer",
                "default": 42
            }
        },
        "required": []
    }
)
def post(self):
    # This raises KeyError if foo is omitted but it would be nice if it returns 42.
    self.body['foo']  

Of cause I can do something like self.body.get('foo', 42) but that's not that awesome for large projects.

By the way: Thanks for this nice package.

hfaran commented 9 years ago

Shouldn't be too hard to add; since this is metadata though, I'm thinking there should be an option in schema.validate to either use this or not. Perhaps something like the following?

def validate(..., use_default=False):
    ....

or do you think it should be enabled by default? Let me know your thoughts, and thanks for the suggestion. :)

normanjaeckel commented 9 years ago

I think an option is not necessary because if someone sets a default value in the schema he normally want to add this to the validated data. Maybe only as opt-out. But for my issues an opt-in option would also be ok.

hfaran commented 9 years ago

That's a fair point. I think use_default=True is a good compromise then.

mauler commented 8 years ago

Hey guys, I worked with tornado-json and I saw that some ideas I had to improve the project other people have too (Issues list) so I decided to give some contribution:

Check this out https://github.com/hfaran/Tornado-JSON/pull/86

hfaran commented 8 years ago

Thanks @mauler, taking a look for you.