Build AWS AppSync API and API Client using Python

   Go back to the Task List

  « 3. Configure AppSync API    5. Configure AppSync Data Source »

4. Create Lambda Function

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.

  1. Goto DynamoDB console, click on the Create table button.

    AWS AppSync

  2. 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.

    AWS AppSync

  3. The table is created in no time. Next you create the Lambda function. Goto Lambda Management console, click on the Create function button.

    AWS AppSync

  4. 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.

    AWS AppSync

  5. The function is created in no time. In the function, goto Function code area. Copy-Paste the following code.

    AWS AppSync

    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
    

    `

  6. 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.

  7. Click on the Save button to save the Lambda function.

  8. 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.