I am looking at creating an API for one of my apps that already has a front page. The input args look something like this:
Case 1
{'_field_1_': 'current_coupon', '_1_>=_1': 'True', '_1_value_1': '10', '_1_value_2': '', '_1_compare_field': '', 'output-columns': 'cusip,isin,description'}
Case 2
{'_field_1_': 'cusip', '_1_exactly': 'True', '_1_value': 'ads', '_1_compare_field': '', '_field_2_': 'semi_mod_duration', '_2_>=_1': 'True', '_2_value_1': '', '_2_value_2': '', '_2_compare_field': 'eff_dur', 'output-columns': 'cusip,isin,description,ticker,current_coupon'}
I found in the webargs
docs how to do trivial arg validation, my code for another app looks like this:
heatmap_args = \
{
'seniority': fields.Str(required=True,
validate=lambda senority: True if any(senority == sen_val for sen_val in seniority) else
raise_(ValidationError("Invalid value for seniority: {}. "
"Valid values: {}".format(senority, seniority)))),
'sector': fields.Str(required=True,
validate=lambda sectora: True if any(sectora == sector_val for sector_val in sector) else
raise_(ValidationError("Invalid value for sector: {}. "
"Valid values: {}".format(sectora, sector)))),
'currency': fields.Str(required=True,
validate=lambda curr: True if any(curr == curr_val for curr_val in currency) else
raise_(ValidationError("Invalid value for currency: {}. "
"Valid values: {}".format(curr, currency)))),
'field': fields.Str(required=True,
validate=lambda fielda: True if any(fielda == field_val for field_val in
list(field.keys()))
else raise_(ValidationError("Invalid value for field: {}. "
"Valid values: {}".format(fielda, list(field.keys())))))
}
However, in this app, number of fields is variable as can be seen from the second case. How do I ensure that all _field_x_
are validated in the same fashion where x
is a number, if _field_x_
is present in the args, without redefining these args multiple times in the dictionary that contains the args. Another manual way would be to validate that when they hit the POST endpoint, but that feels weird.
There is also conditional logic here. For example, if selected field is of type text, then the user has the checkbox option of exactly (thus _1_exactly
in Case 2), however, if the field is of numeric value, then there should be logic on top of _1_value_1
as in Case 1.
How to approach this?