Search code examples
python-3.xamazon-dynamodbflask-restful

Flask AWS Dynamo DB : POST API


I am new to the DynamoDB and Flask , I have endpoint which insert the records to the dynamo database, my payload is look like this

{
  "Address": "2013 3A New Jersey",
  "Contact_Number1": "1105632",
  "Contact_Number2": "1105632",
  "DOB": "1968-08-12",
  "Father": "FTest2",
  "First_name": "FTest2",
  "Gender": "Male",
  "Hospital_Reg_Num": "HRM123",
  "Husband": "HTest2",
  "Last_name": "LTest2",
  "Last_visit_date": "2017-11-12",
  "Mother": "MTest2",
  "patient_id": "100"
}

and my flaska api code is like this

def createPatient(): try: userId = request.json.get('user_id') firstName = request.json.get('First_name') lastName = request.json.get('Last_name') gender = request.json.get('Gender') dob = request.json.get('DOB') except KeyError: raise InvalidUsage('Bad Request', status_code=400)

print(request.json)
father = request.json.get('Father')  if 'Father' in request.json  else None
mother = request.json.get('Mother') if 'Mother' in request.json else None
husband =  request.json.get('Husband') if 'Husband' in  request.json else None
address = request.json.get('Address') if 'Address' in request.json else None
lastVisitDate= request.json.get('Last_visit_date') if 'Last_visit_date' in request.json else None

#create a new db entry
userData = {
    'user_id': { 'N': userId },
    'First_name': { 'S': firstName },
    'Last_name': { 'S': lastName },
    'Hospital_Reg_Num': { 'S': hospitalReg },
    'Gender': { 'S': gender },
    'DOB': { 'S': dob },
    'Father': { 'S': father },
    'Mother': { 'S': mother },
    'Husband': { 'S': husband },
    'Address': { 'S': address },
    'Last_visit_date': { 'S': lastVisitDate }
}

resp = client.put_item(TableName='user',Item=userData)
return jsonify(resp), 200

If in payload i missed any parameters say father name then its not inserting the other records its giving me an error

Invalid type for parameter Item.Father.S, value: None, type: <class 'NoneType'>, valid types: <class 'str'>

Can you please help me how can i ignore the fatherName to insert record in dynamo db? want to update the record whatever sent by the payload


Solution

  • Instead of setting missing parameters to None, set them as an empty string. For example:

    father = request.json.get(‘Father’, ‘’)
    

    The second arg returns a default value if the specified key is not found.