Create adding function

This section will create a function to add document information to the DynamoDB table.

  1. Open AWS Lambda console

  2. Click Create function LambdaConsole

  3. Enter function name: upload_document

  • Select Python 3.14 for Runtime
  • Click Create function

CreateFunction

  1. Enter the following code for the lambda_function.py file:
import json
import boto3
import os
from datetime import datetime, timezone

dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):
    table_name = os.environ['TABLE_NAME']
    now = datetime.now(tz=timezone.utc)
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    #doc_data = json.loads(event["body"])
    doc_data = event["body"]

    path = "protected/{}/{}".format(doc_data['identityId'], doc_data['file'])
    doc_data.update({"path": path, "modified": dt_string})
    table = dynamodb.Table(table_name)
    table.put_item(Item = doc_data)
        
    # TODO implement
    return {
        'statusCode': 200,
        'body': 'successfully upload!',
        'headers': {
            'Content-Type': 'application/json',
            "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Access-Token, XKey, Authorization",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS"
        }
    }
  • Click Deploy

CreateFunction

The above code gets the TABLE_NAME environment variable and the data sent by the user. It then adds each item to the DynamoDB table.

  1. We need to add an environment variable to the function. Click the Configuration tab, then select Environment variables in the left menu. Click Edit

EnvironmentVariables

  1. Click Add environment variable
  • Enter TABLE_NAME in the key field
  • Enter the name of the DynamoDB table you just created in the value field
  • Click Save

EnvironmentVariables

  1. Next, add permissions for the function to access the DynamoDB table
  • Click Permissions in the left menu
  • Click the function’s execution role

Permission

  1. Expand the AWSLambdaBasicExecutionRole… policy, then click Edit

Permission

  1. Copy the JSON below into the JSON editor
        {
            "Effect": "Allow",
            "Action": "dynamoDB:PutItem",
            "Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/Documents"
        }

Replace REGION and ACCOUNT_ID with the region where you created the table and your account ID.

  • Click Next

Permission

  1. Click Save changes

Permission