Hi, I was trying to make an API gateway with lambdas and DynamoDb in python. The put function works fine if I hit it with test in AWS console, but if API Gateway tries to access it by URL, I get an error:
{ message: "Missing Authentication Token" }
,
My serverless.yml file is :
service: simple-backend
custom:
settings:
POSTS_TABLE: posts
pythonRequirements:
dockerizePip: true
provider:
name: aws
runtime: python3.7
profile: serverless-admin
region: ap-southeast-2
iamRoleStatements:
#Mention permissions explicitly.It's good practice not to give more permissions.
- Effect: "Allow"
Action:
- dynamodb:DescribeTable
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource:
#Mentioning name of region and the table
- "arn:aws:dynamodb:${self:provider.region}:*:table/${self:custom.settings.POSTS_TABLE}"
functions:
putuserinfo:
handler: handler.putuserinfo
events:
- http:
path: putuserinfo
method: put
cors: true
getuserinfo:
handler: handler.getuserinfo
events:
- http:
#Creates a path in API gateway
path: getuserinfo
method: get
cors: true
Install the following plugin using npm if you want to use boto3
resources:
#under resource, cloudformation template can be defined.
Resources:
PostsTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: "username"
AttributeType: "S"
- AttributeName: "gameid"
AttributeType: "S"
#Following is same as CloudFromation syntax
#KeySchema should have length less than or equal to 2.
KeySchema:
- AttributeName: "username"
KeyType: "HASH"
- AttributeName: "gameid"
KeyType: "RANGE"
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:custom.settings.POSTS_TABLE}
plugins:
- serverless-python-requirements
My handler.py file is:
import boto3
def getuserinfo(event, context):
print ("context is", context)
message = "Data was saved"
return {
'statusCode' : 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message' : message })
}
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('posts')
def putuserinfo(event, context):
table.put_item(
Item = {
'username': '12345',
'gameid':'123'
})
message = "Data was saved"
return {
'statusCode' : 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message' : message })
}
My get function works perfectly, if I hit the url after the deploy, but the url specified in deploy for put function produces the above error, which says “missing authentication Token”