Config APIs And Lambda Function

In this section, we will add the Documents DynamoDB table, the three Lambda functions list_documents, upload_document, delete_document and the fcaj-dms-api REST API to the SAM template. These are the resources you created in the console in workshop 133 and workshop 135.

  1. Open the template.yaml file in the fcajdms-sam folder. Add the following code below FcajDMSWebStorePolicy (before the Outputs section):
  # DynamoDB table that stores document information
  DocumentsTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: Documents
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: user_id
          AttributeType: S
        - AttributeName: file
          AttributeType: S
      KeySchema:
        - AttributeName: user_id
          KeyType: HASH
        - AttributeName: file
          KeyType: RANGE
      StreamSpecification:
        StreamViewType: NEW_IMAGE
  • The Documents table has user_id as the Partition key and file as the Sort key, the same as the table you created in workshop 133.
  • StreamSpecification: enables DynamoDB Streams to record the changes of the table. The stream is used by the search feature in workshop 138.

CreateTable

  1. Create the lambda folder in the fcajdms-sam folder. Then create the folder and the file lambda/list_documents/list_documents.py with the following code:
import json
import boto3
import os
from decimal import *
from boto3.dynamodb.types import TypeDeserializer

dynamodb = boto3.client('dynamodb') 
serializer = TypeDeserializer()

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

def deserialize(data):
    if isinstance(data, list):
        return [deserialize(v) for v in data]

    if isinstance(data, dict):
        try:
            return serializer.deserialize(data)
        except TypeError:
            return {k: deserialize(v) for k, v in data.items()}
    else:
        return data
        
def lambda_handler(event, context):
    table_name = os.environ['TABLE_NAME']
    user_id = event['pathParameters']['id']
    print(user_id)
    docs = dynamodb.query(
        TableName=table_name,
        KeyConditionExpression="user_id = :id",
        ExpressionAttributeValues={ ":id": { 'S': user_id } }
    )
    
    format_data_docs = deserialize(docs["Items"])
    # TODO implement
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE, OPTIONS",
            "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Access-Token,XKey,Authorization"
        },
        "body": json.dumps(format_data_docs, cls=DecimalEncoder)
    }
  • This is the code of the list_documents function from workshop 133.

CreateLambda

  1. Similarly, create the folder and the file lambda/upload_document/upload_document.py with the following code:
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"])

    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"
        }
    }
  • This is the code of the upload_document function from workshop 133 with the change of workshop 135: doc_data = json.loads(event["body"]) converts the JSON string sent by API Gateway into data before writing it to DynamoDB.

CreateLambda

  1. Similarly, create the folder and the file lambda/delete_document/delete_document.py with the following code:
import json
import boto3
import os

client = boto3.resource('dynamodb')

def lambda_handler(event, context):
    # TODO implement
    table_name = os.environ['TABLE_NAME']
    error = None
    doc_pk = event['pathParameters']['id']
    print("doc_pk ", doc_pk)
    doc_sk = event['queryStringParameters']['file']
    print("doc_sk ", doc_sk)
    table = client.Table(table_name)
    key = {
        'user_id':doc_pk,
        'file':  doc_sk
    }
    
    try:
        table.delete_item(Key = key)
    except Exception as e:
        error = e
        
        
    except Exception as e:
        error = e
        
    if error is None:
        message = 'delete document successful!'
    else:
        print(error)
        message = 'delete document fail'
    
    return {
            'statusCode': 200,
            'body': message,
            'headers': {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            },
        }
  • This is the code of the delete_document function from workshop 133.

CreateLambda

  1. Go back to the template.yaml file and add the following code below DocumentsTable to declare the three Lambda functions:
  # GET /docs/{id}: list the documents of a user
  ListDocumentsFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: list_documents
      CodeUri: lambda/list_documents
      Handler: list_documents.lambda_handler
      Environment:
        Variables:
          TABLE_NAME: !Ref DocumentsTable
      Policies:
        - Statement:
            - Effect: Allow
              Action:
                - dynamodb:Query
              Resource: !GetAtt DocumentsTable.Arn
      Events:
        ListDocuments:
          Type: Api
          Properties:
            RestApiId: !Ref DocumentsApi
            Path: /docs/{id}
            Method: get

  # POST /docs: save the information of an uploaded document
  UploadDocumentFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: upload_document
      CodeUri: lambda/upload_document
      Handler: upload_document.lambda_handler
      Environment:
        Variables:
          TABLE_NAME: !Ref DocumentsTable
      Policies:
        - Statement:
            - Effect: Allow
              Action:
                - dynamodb:PutItem
              Resource: !GetAtt DocumentsTable.Arn
      Events:
        UploadDocument:
          Type: Api
          Properties:
            RestApiId: !Ref DocumentsApi
            Path: /docs
            Method: post

  # DELETE /docs/{id}?file=: delete the information of a document
  DeleteDocumentFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: delete_document
      CodeUri: lambda/delete_document
      Handler: delete_document.lambda_handler
      Environment:
        Variables:
          TABLE_NAME: !Ref DocumentsTable
      Policies:
        - Statement:
            - Effect: Allow
              Action:
                - dynamodb:DeleteItem
              Resource: !GetAtt DocumentsTable.Arn
      Events:
        DeleteDocument:
          Type: Api
          Properties:
            RestApiId: !Ref DocumentsApi
            Path: /docs/{id}
            Method: delete
  • CodeUri and Handler: the folder that contains the code and the lambda_handler function in the matching Python file. The runtime, timeout and architecture come from the Globals section.
  • Environment: the TABLE_NAME environment variable holds the name of the Documents table, replacing the console step that added the environment variable in workshop 133.
  • Policies: each function only gets the permission it needs on the Documents table (dynamodb:Query, dynamodb:PutItem, dynamodb:DeleteItem). SAM creates the execution role with these permissions and the permission to write logs to CloudWatch.
  • Events: creates the matching method in the DocumentsApi REST API and integrates that method with the Lambda function (Lambda proxy integration), like the API Gateway steps you did in workshop 135.

CreateLambda

  1. Add the following code below the three Lambda functions to declare the REST API:
  # REST API with CORS for the web application
  DocumentsApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: fcaj-dms-api
      StageName: dev
      EndpointConfiguration:
        Type: REGIONAL
      Cors:
        AllowMethods: "'GET,POST,DELETE,OPTIONS'"
        AllowHeaders: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
        AllowOrigin: "'*'"
  • The REST API is named fcaj-dms-api and deployed to the dev stage, as in workshop 135.
  • Cors: SAM creates the OPTIONS method of each resource for you, replacing the Enable CORS action in the console of workshop 135. The Authorization header is allowed because the application sends the Cognito token with every request. For GET, POST and DELETE requests, the CORS headers are returned by the Lambda functions themselves.

CreateAPI

  1. Add the following value to the bottom of the Outputs section to get the Invoke URL of the dev stage:
  ApiUrl:
    Description: Invoke URL of the dev stage
    Value: !Sub "https://${DocumentsApi}.execute-api.${AWS::Region}.amazonaws.com/dev"

CreateAPI

The APIs used by the application:

Method Resource Lambda function Purpose
POST /docs upload_document Write document information to DynamoDB
GET /docs/{id} list_documents Get the document list of a user
DELETE /docs/{id}?file= delete_document Delete the information of a document
  1. Run the commands below to build and deploy the SAM project after updating the template:
sam build
sam deploy
  • Enter y when asked Deploy this changeset?

SAMDeploy

If you run sam deploy --guided, SAM asks … may not have authorization defined, Is this okay? [y/N] for each function. Enter y to continue. The sam deploy command reuses the configuration in samconfig.toml, so it does not ask this question.

  1. Open the API Gateway console and select the fcaj-dms-api API. You will see the /docs and /docs/{id} resources with the GET, POST, DELETE and OPTIONS methods created by SAM.
  • In Stages, besides the dev stage you may also see a stage named Stage that SAM creates automatically. Ignore it; the application only uses the dev stage (the ApiUrl value in Outputs).

CheckAPI

In this workshop series, the API is not protected by authentication; anyone with the URL can call it. The application already sends the Cognito token in the Authorization header, so you can add a Cognito authorizer to the API yourself when needed.

In the next part, we will update the front-end to test the APIs.