Search code examples
amazon-web-servicesaws-lambdaamazon-dynamodbamazon-iam

AWS insert lambda function values into DynamoDB


Through a lambda function I call an openrest api this data I would like to store in a dynamodb. By using AWS, In the IAM a new role is created with dynamodb fullaccess. In Lambda I created a function where the data from the api comes in correctly because it also shows up correctly when testing the function. Now it fails to get the data into the dynamodb table. Have no clue why it is not working? Here is the code:

import json
import boto3
import requests
from datetime import datetime

# Verbindingsinstellingen voor DynamoDB
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('WindPrijzenElia')

def lambda_handler(event, context):
    URL = "https://opendata.elia.be/api/v2/catalog/datasets/ods077/records?order_by=datetime%20desc&limit=1&offset=0&timezone=Europe%2FParis"

    Marge_trevion = 1.5
    GVO = 5
    GSC_WT = 0
    GSC_AK = 93
    Onderhoud_vestas = 10

    r = requests.get(url=URL)
    data = r.json()
    Onbalans_prijs = data['records'][0]['record']['fields']['positiveimbalanceprice']

    Som_WT = GSC_WT + GVO - Onderhoud_vestas - Marge_trevion + Onbalans_prijs
    Reduceren_WT = Som_WT < -30

    Som_AK = GSC_AK + GVO - Onderhoud_vestas - Marge_trevion + Onbalans_prijs
    Reduceren_AK = Som_AK < -30

    print(datetime.now(), "Elia timestamp =", data['records'][0]['record']['timestamp'], "",
          data['records'][0]['record']['id'], " ", data['records'][0]['record']['fields']['datetime'], " ",
          data['records'][0]['record']['fields']['positiveimbalanceprice'], Som_WT, Reduceren_WT)
    print(datetime.now(), "Elia timestamp =", data['records'][0]['record']['timestamp'], "",
          data['records'][0]['record']['id'], " ", data['records'][0]['record']['fields']['datetime'], " ",
          data['records'][0]['record']['fields']['positiveimbalanceprice'], Som_WT, Reduceren_WT)

    return {
        'statusCode': 200,
        'body': json.dumps("success")
    }

Solution

  • Data does not magically save into DynamoDB. You must call the put_item API and pass the data you wish to save we as a parameter.

    https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/put_item.html