Search code examples
pythonamazon-dynamodbboto3fastapi

put_item DynamoDb with FastAPI post request


I've set up a backend using FastAPI and Pydantic

class Student(BaseModel):
    name: str 
    age: int 
    year: str

... 

@app.post('/create-student/{student_id}')
def create_student(student_id : int, student : Student):
    db = connect_ddb() #Boto3 instantiates dynamoDb resource
    student_obj = json.loads(student)
    try:
        db.put_item(
            Item = {f"{student_id}": student_obj}
        )
        return db.get_item(student_id)    
    except: 
        return {"error": "Unable to put data in Ddb"}

Now when I try to test this functionality using

def put(item, id_, db=db):
    obj = json.dumps(item)
    db.put_item(Item={f"{id_}": obj})

put(id_=4, item={
    "name": "Guy",
    "age": 17,
    "year": "year 12"
})

I receive the following '{"error": "Unable to put data in Ddb"}'.

So we can safely conclude that the Db connection was successful. However, I'm unable to insert the object into DynamoDb. Because an error post-connection was returned.

Is there a way to raise the specific error? (DynamoDb would need to return it via FastAPI.)

Or better yet, should the Item parameter in put_item method be formatted differently?

The connection set up using

def connect_ddb():
    ddb = boto3.resource('dynamodb', region_name='us-west-2')
    table = ddb.Table('myTable')
    return table 

Solution

  • You get the exception because you make a read directly after write, which is eventually consistent. If you want to do a read directly after right, be sure to set the consistent parameter to true.

    But this is not how to check if an item persists in DynamoDB, you should receive a 200 response from DynamoDB, then you are certain the item persisted, no need to read every time.

    The Item your passing to PutItem does not look to be following the correct syntax. id and item should be at the same level.