You create a Lambda function which provides implementation for the getTask and addTask methods. The addTask method will add a task description to a DynamoDB table. The getTask method will query task description from the DynamoDB table.
-
Goto DynamoDB console, click on the Create table button.
-
On the next screen, type in dojowork as the table name. Type in id as the primary key with data type selected as String. Keep rest of the configuration to the default and click on the Create button.
-
The table is created in no time. Next you create the Lambda function. Goto Lambda Management console, click on the Create function button.
-
On the next screen, select Author from scratch option. Type in dojoworklambda as the function name. Select Python 3.8 as the runtime. Check for the Use an existing role option and select dojolambdarole for the role. Finally click on the Create function button.
-
The function is created in no time. In the function, goto Function code area. Copy-Paste the following code.
import json import boto3 def lambda_handler(event, context): response = "The method not defined" client = boto3.resource('dynamodb') table = client.Table("dojowork") if (event["method"] == "getTask"): response = table.get_item(Key={'id': event["arguments"]["id"]}) return response elif (event["method"] == "addTask"): response = table.put_item(Item={'id': event["arguments"]["id"], 'description': event["arguments"]["description"]}) return response else: return response
`
-
In the code above, a single function is used to handle both getTask and addTask methods. AppSync API will pass method as one of the field in the event parameter which decides whether the task record has to be stored or fetched from the DynamoDB table. The event parameter also has the arguments field to access task record details such as id and description.
-
Click on the Save button to save the Lambda function.
-
The Lambda function is ready. Time to configure the Lambda function as the data source in the AppSync API and also attached the function to the API data schema.