In this Gist i will record all the validations that i use when building API's that may be useful in the future or maybe improved.
response_body = {}
data = request.json
required_data = ['data1', 'data2'] # Include all the required data that the endpoint needs
for key in required_data:
if key not in data:
response_body['message'] = f"Falta '{key}' en el body"
return response_body, 400 # Use the early return
In this code we use a list required_data
to check for the required keys in the JSON body. If any of the data is not in the body then we return the name of the key and a error
current_user = get_jwt_identity()
response_body = {}
data = request.json
item_in_db = db.session.execute(db.select(Table_in_db).where(Table_in_db.id == item_id)).scalar() # We search for the item to edit
allowed_attributes = {'data1': True,
'data2': False,
'data3': current_user['role'] == 'admin', # In this case, the admin role is in the token
}
for key, value in data.items():
if hasattr(item_in_db, key) and allowed_attributes.get(key, False):
if key == 'data2': # We can check for specific cases, not required
value = encrypt_data2(value) # We call the function, in this case, encrypt it
setattr(item_in_db, key, value) # We set the attribute if it's allowed
db.session.commit()
In this code we search for the item to edit, in this case item_in_db
, then we use a dictionary allowed_attributes
to set which attributes can be edited or not. We can use also conditions that return true
or false
to automatically allow or not.
Then we just set the attribute, we can even check the key to specific keys to make calls to functions. This is not required and those lines can be deleted if not needed