I am working on a lambda code for an API in AWS. I am passing a json data within my body which is
shown like this when I print my event within the lambda.
'body': '{rn "STTN": "415263",rn "Account": "22568758"rn}rn',
Here is how I am validating within the lambda
try:
eventJson['body']['STTN']
except Exception:
returnValidateConditional = False
validationResponse['apiStatus'] = "failed"
validationResponse['apiErrorCode'] ="1"
validationResponse['apiDescription'] = "STTN is required"
statusCode = 415
return [returnValidateConditional, validationResponse, statusCode]
try:
eventJson['body']['Account']
except Exception:
returnValidateConditional = False
validationResponse['apiStatus'] = "failed"
validationResponse['apiErrorCode'] ="1"
validationResponse['apiDescription'] = "Account is required"
statusCode = 415
return [returnValidateConditional, validationResponse, statusCode]
My validation fails all the time despite the fact that STTN and Account are not empty. They have values
that exist in the body request. All I get is STTN is required
How can I validate json items in the body sent as a request?
2
Answers
I can notice a few immediate issues with the code:
'body'
value is of typestr
(string), so it won’t work if you subscript it.try: ... except Exception: ...
you are masking the actual error, which isTypeError
. I would suggest better error handling, such as printing (or logging) the actual exception/error message. A good start would beexcept Exception as e:
, followed by something likeprint(e)
.dict
object. I would suggest using thein
operator instead.Repro’d example in REPL:
Solution: you can use
json.loads
on thestr
value to convert it to adict
objecteventJson['body']
is a string. You need to parse it first