support jsonschema decorator for injection into swagger gen / validation
- Dominant language
- Python
- Stars
- 11.1k
- Forks
- 1k
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 2
Description
i've been using a simple decorator to get nicer ergonomics on view/route function signatures and type validation. I'd like to go ahead and add something like this to chalice, with the notion that it could also be used for swagger generation. Atm chalice swagger gen is effectively wild card method parameters with the empty object definition. Ideally with this decorator it would allow offloading request validation to api gateway, though i'm a bit unclear if thats supported by the underlying SAM transform although it looks like we could just inject a separate non sam request validator resource.
```python
def schema(schema, required=None):
"""Decorator for chalice view functions to enable jsonschema
At the moment it allows validation and keyword parameter
passing based on extracted values.
"""
# sugar syntax for skipping the declaration enclosure
if 'properties' not in schema:
schema = {'properties': schema,
'type': 'object',
'additionalProperties': False}
if '$schema' not in schema:
schema['$schema'] = 'http://json-schema.org/schema#'
if required and 'required' not in schema:
schema['required'] = list(required)
def wrapper(func):
func.schema = schema
@functools.wraps(func)
def validate_invoke(*args, **kw):
r = app.current_request
if r.method == 'POST':
rj = app.current_request.json_body
elif r.method == 'GET':
rj = app.current_request.query_params
jsonschema.validate(rj, schema)
kw = {}
for k in schema['properties'].keys():
if k in rj:
kw[k] = rj[k]
return func(*args, **kw)
return validate_invoke
return wrapper
```
in terms of using it
```python
@app.route('/create-foo', authorizer=authorizer, methods=['POST'])
@schema({'Duration': {'type': 'number'},
'Budget': {'type': 'number'}}, required=('Duration'))
def create_foo(Duration, Budget=0):
# direct parameter extraction :-)
return {}
```
Potentially this would allow for future extension to using python typing information.
tbd on referencing common model definitions across view functions.
Contributor guide
Research direction
Start by reviewing the current Chalice Swagger generation behavior described as wildcard method parameters with an empty object definition, then compare it with the proposed decorator and validation flow. Investigate the mentioned API Gateway and SAM transform support before defining the scope; done should clearly specify decorator behavior, request validation, Swagger output, and handling of shared model definitions.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- aws, json, python
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100