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.
# 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
user_id as the Partition key and file as the Sort key, the same as the table you created in workshop 133.
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)
}

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"
}
}
doc_data = json.loads(event["body"]) converts the JSON string sent by API Gateway into data before writing it to DynamoDB.
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': '*'
},
}

# 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.
# 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: "'*'"
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.
ApiUrl:
Description: Invoke URL of the dev stage
Value: !Sub "https://${DocumentsApi}.execute-api.${AWS::Region}.amazonaws.com/dev"

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 |
sam build
sam deploy
y when asked Deploy this changeset?
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.

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.