cannot get api gateway to log

I am trying to learn terraform. I trying to have api gateway pass requests to lambda to do REST CRUD actions to manage a record in Dynamo DB.

at one point I had been able to have the API gateway contact the lambda do create the record. When I tried to get the record I was getting server errors or authorization errors.

Looking at the console. the methods all have NONE for authorizers. one of the recommendations I got was to have API gateway log what is going on.
The log group is getting created but nothing is getting logged.

Any thoughts on how to get API gateway to log what is going on
Any suggestions on how to get API gateway to do basic restful actions?

here is my terraform

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># Define the provider
provider "aws" {
region = "us-east-1" # Specify your desired region
}
# Create a DynamoDB table
resource "aws_dynamodb_table" "my_table" {
name = "MyTable"
billing_mode = "PAY_PER_REQUEST"
hash_key = "ID"
attribute {
name = "ID"
type = "S"
}
}
# Create an IAM role for Lambda execution
resource "aws_iam_role" "lambda_execution_role" {
name = "my_lambda_execution_role"
assume_role_policy = jsonencode({
"Version" : "2012-10-17",
"Statement" : [
{
"Action" : "sts:AssumeRole",
"Principal" : {
"Service" : "lambda.amazonaws.com"
},
"Effect" : "Allow",
"Sid" : ""
}
]
})
inline_policy {
name = "lambda_dynamodb_policy"
policy = jsonencode({
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem"
],
"Resource" : "arn:aws:dynamodb:*:*:table/MyTable"
}
]
})
}
}
# Attach the IAM role to the Lambda function
resource "aws_lambda_function" "my_function" {
filename = "${path.module}/my_function.zip" # The path to your Lambda function code
function_name = "MyFunction"
handler = "lambda_function.lambda_handler"
runtime = "python3.11"
source_code_hash = filebase64sha256("${path.module}/my_function.zip")
role = aws_iam_role.lambda_execution_role.arn # Specify the ARN of the IAM role here
environment {
variables = {
DYNAMO_TABLE_NAME = aws_dynamodb_table.my_table.name
}
}
}
# Attach the IAM role to the Lambda function for API Gateway invocation
resource "aws_lambda_permission" "allow_api_gateway" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.my_function.arn
principal = "apigateway.amazonaws.com"
source_arn = "${aws_api_gateway_rest_api.my_api.execution_arn}/*/*/*"
}
# Create an API Gateway
resource "aws_api_gateway_rest_api" "my_api" {
name = "MyAPI"
}
# Create a resource
resource "aws_api_gateway_resource" "my_resource" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
parent_id = aws_api_gateway_rest_api.my_api.root_resource_id
path_part = "myresource"
}
# Create a put method
resource "aws_api_gateway_method" "my_put_method" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = "PUT"
authorization = "NONE"
}
# Integration between API Gateway and Lambda for PUT method
resource "aws_api_gateway_integration" "my_put_integration" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = aws_api_gateway_method.my_put_method.http_method
integration_http_method = "PUT"
type = "AWS_PROXY"
uri = aws_lambda_function.my_function.invoke_arn
}
# Deployment for PUT method
resource "aws_api_gateway_deployment" "my_put_deployment" {
depends_on = [aws_api_gateway_integration.my_put_integration]
rest_api_id = aws_api_gateway_rest_api.my_api.id
#stage_name = "dev"
}
# Create a GET method
resource "aws_api_gateway_method" "my_get_method" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = "GET"
authorization = "NONE"
}
# Integration between API Gateway and Lambda for GET method
resource "aws_api_gateway_integration" "my_get_integration" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = aws_api_gateway_method.my_get_method.http_method
integration_http_method = "GET"
type = "AWS_PROXY"
uri = aws_lambda_function.my_function.invoke_arn
}
# Deployment for GET method
resource "aws_api_gateway_deployment" "my_get_deployment" {
depends_on = [aws_api_gateway_integration.my_get_integration]
rest_api_id = aws_api_gateway_rest_api.my_api.id
# stage_name = "dev"
}
# Enable logging for the API Gateway stage
# Enable logging for the API Gateway stage
resource "aws_api_gateway_stage" "my_stage" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
stage_name = "dev"
deployment_id = aws_api_gateway_deployment.my_put_deployment.id
access_log_settings {
destination_arn = aws_cloudwatch_log_group.api_logs.arn
format = "$context.requestId $context.extendedRequestId"
}
lifecycle {
ignore_changes = [deployment_id] # Ignore changes to deployment_id
}
}
# CloudWatch Log Group for API Gateway logs
resource "aws_cloudwatch_log_group" "api_logs" {
name = "/aws/api-gateway/my_api_logs"
retention_in_days = 7
}
# Output the API Gateway endpoint
output "api_gateway_endpoint" {
value = aws_api_gateway_deployment.my_put_deployment.invoke_url
}
</code>
<code># Define the provider provider "aws" { region = "us-east-1" # Specify your desired region } # Create a DynamoDB table resource "aws_dynamodb_table" "my_table" { name = "MyTable" billing_mode = "PAY_PER_REQUEST" hash_key = "ID" attribute { name = "ID" type = "S" } } # Create an IAM role for Lambda execution resource "aws_iam_role" "lambda_execution_role" { name = "my_lambda_execution_role" assume_role_policy = jsonencode({ "Version" : "2012-10-17", "Statement" : [ { "Action" : "sts:AssumeRole", "Principal" : { "Service" : "lambda.amazonaws.com" }, "Effect" : "Allow", "Sid" : "" } ] }) inline_policy { name = "lambda_dynamodb_policy" policy = jsonencode({ "Version" : "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "dynamodb:PutItem", "dynamodb:GetItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem" ], "Resource" : "arn:aws:dynamodb:*:*:table/MyTable" } ] }) } } # Attach the IAM role to the Lambda function resource "aws_lambda_function" "my_function" { filename = "${path.module}/my_function.zip" # The path to your Lambda function code function_name = "MyFunction" handler = "lambda_function.lambda_handler" runtime = "python3.11" source_code_hash = filebase64sha256("${path.module}/my_function.zip") role = aws_iam_role.lambda_execution_role.arn # Specify the ARN of the IAM role here environment { variables = { DYNAMO_TABLE_NAME = aws_dynamodb_table.my_table.name } } } # Attach the IAM role to the Lambda function for API Gateway invocation resource "aws_lambda_permission" "allow_api_gateway" { statement_id = "AllowExecutionFromAPIGateway" action = "lambda:InvokeFunction" function_name = aws_lambda_function.my_function.arn principal = "apigateway.amazonaws.com" source_arn = "${aws_api_gateway_rest_api.my_api.execution_arn}/*/*/*" } # Create an API Gateway resource "aws_api_gateway_rest_api" "my_api" { name = "MyAPI" } # Create a resource resource "aws_api_gateway_resource" "my_resource" { rest_api_id = aws_api_gateway_rest_api.my_api.id parent_id = aws_api_gateway_rest_api.my_api.root_resource_id path_part = "myresource" } # Create a put method resource "aws_api_gateway_method" "my_put_method" { rest_api_id = aws_api_gateway_rest_api.my_api.id resource_id = aws_api_gateway_resource.my_resource.id http_method = "PUT" authorization = "NONE" } # Integration between API Gateway and Lambda for PUT method resource "aws_api_gateway_integration" "my_put_integration" { rest_api_id = aws_api_gateway_rest_api.my_api.id resource_id = aws_api_gateway_resource.my_resource.id http_method = aws_api_gateway_method.my_put_method.http_method integration_http_method = "PUT" type = "AWS_PROXY" uri = aws_lambda_function.my_function.invoke_arn } # Deployment for PUT method resource "aws_api_gateway_deployment" "my_put_deployment" { depends_on = [aws_api_gateway_integration.my_put_integration] rest_api_id = aws_api_gateway_rest_api.my_api.id #stage_name = "dev" } # Create a GET method resource "aws_api_gateway_method" "my_get_method" { rest_api_id = aws_api_gateway_rest_api.my_api.id resource_id = aws_api_gateway_resource.my_resource.id http_method = "GET" authorization = "NONE" } # Integration between API Gateway and Lambda for GET method resource "aws_api_gateway_integration" "my_get_integration" { rest_api_id = aws_api_gateway_rest_api.my_api.id resource_id = aws_api_gateway_resource.my_resource.id http_method = aws_api_gateway_method.my_get_method.http_method integration_http_method = "GET" type = "AWS_PROXY" uri = aws_lambda_function.my_function.invoke_arn } # Deployment for GET method resource "aws_api_gateway_deployment" "my_get_deployment" { depends_on = [aws_api_gateway_integration.my_get_integration] rest_api_id = aws_api_gateway_rest_api.my_api.id # stage_name = "dev" } # Enable logging for the API Gateway stage # Enable logging for the API Gateway stage resource "aws_api_gateway_stage" "my_stage" { rest_api_id = aws_api_gateway_rest_api.my_api.id stage_name = "dev" deployment_id = aws_api_gateway_deployment.my_put_deployment.id access_log_settings { destination_arn = aws_cloudwatch_log_group.api_logs.arn format = "$context.requestId $context.extendedRequestId" } lifecycle { ignore_changes = [deployment_id] # Ignore changes to deployment_id } } # CloudWatch Log Group for API Gateway logs resource "aws_cloudwatch_log_group" "api_logs" { name = "/aws/api-gateway/my_api_logs" retention_in_days = 7 } # Output the API Gateway endpoint output "api_gateway_endpoint" { value = aws_api_gateway_deployment.my_put_deployment.invoke_url } </code>
# Define the provider
provider "aws" {
  region = "us-east-1" # Specify your desired region
}

# Create a DynamoDB table
resource "aws_dynamodb_table" "my_table" {
  name         = "MyTable"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "ID"
  attribute {
    name = "ID"
    type = "S"
  }
}

# Create an IAM role for Lambda execution
resource "aws_iam_role" "lambda_execution_role" {
  name = "my_lambda_execution_role"

  assume_role_policy = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        "Action" : "sts:AssumeRole",
        "Principal" : {
          "Service" : "lambda.amazonaws.com"
        },
        "Effect" : "Allow",
        "Sid" : ""
      }
    ]
  })

  inline_policy {
    name = "lambda_dynamodb_policy"
    policy = jsonencode({
      "Version" : "2012-10-17",
      "Statement" : [
        {
          "Effect" : "Allow",
          "Action" : [
            "dynamodb:PutItem",
            "dynamodb:GetItem",
            "dynamodb:UpdateItem",
            "dynamodb:DeleteItem"
          ],
          "Resource" : "arn:aws:dynamodb:*:*:table/MyTable"
        }
      ]
    })
  }
}

# Attach the IAM role to the Lambda function
resource "aws_lambda_function" "my_function" {
  filename         = "${path.module}/my_function.zip" # The path to your Lambda function code
  function_name    = "MyFunction"
  handler          = "lambda_function.lambda_handler"
  runtime          = "python3.11"
  source_code_hash = filebase64sha256("${path.module}/my_function.zip")
  role             = aws_iam_role.lambda_execution_role.arn # Specify the ARN of the IAM role here

  environment {
    variables = {
      DYNAMO_TABLE_NAME = aws_dynamodb_table.my_table.name
    }
  }
}

# Attach the IAM role to the Lambda function for API Gateway invocation
resource "aws_lambda_permission" "allow_api_gateway" {
  statement_id  = "AllowExecutionFromAPIGateway"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.my_function.arn
  principal     = "apigateway.amazonaws.com"
  source_arn = "${aws_api_gateway_rest_api.my_api.execution_arn}/*/*/*"
}

# Create an API Gateway
resource "aws_api_gateway_rest_api" "my_api" {
  name = "MyAPI"

}

# Create a resource
resource "aws_api_gateway_resource" "my_resource" {
  rest_api_id = aws_api_gateway_rest_api.my_api.id
  parent_id   = aws_api_gateway_rest_api.my_api.root_resource_id
  path_part   = "myresource"
}

# Create a put method
resource "aws_api_gateway_method" "my_put_method" {
  rest_api_id   = aws_api_gateway_rest_api.my_api.id
  resource_id   = aws_api_gateway_resource.my_resource.id
  http_method   = "PUT"
  authorization = "NONE"
}

# Integration between API Gateway and Lambda for PUT method
resource "aws_api_gateway_integration" "my_put_integration" {
  rest_api_id             = aws_api_gateway_rest_api.my_api.id
  resource_id             = aws_api_gateway_resource.my_resource.id
  http_method             = aws_api_gateway_method.my_put_method.http_method
  integration_http_method = "PUT"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.my_function.invoke_arn
}

# Deployment for PUT method
resource "aws_api_gateway_deployment" "my_put_deployment" {
  depends_on  = [aws_api_gateway_integration.my_put_integration]
  rest_api_id = aws_api_gateway_rest_api.my_api.id
  #stage_name  = "dev"
}

# Create a GET method
resource "aws_api_gateway_method" "my_get_method" {
  rest_api_id   = aws_api_gateway_rest_api.my_api.id
  resource_id   = aws_api_gateway_resource.my_resource.id
  http_method   = "GET"
  authorization = "NONE"
}

# Integration between API Gateway and Lambda for GET method
resource "aws_api_gateway_integration" "my_get_integration" {
  rest_api_id             = aws_api_gateway_rest_api.my_api.id
  resource_id             = aws_api_gateway_resource.my_resource.id
  http_method             = aws_api_gateway_method.my_get_method.http_method
  integration_http_method = "GET"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.my_function.invoke_arn
}

# Deployment for GET method
resource "aws_api_gateway_deployment" "my_get_deployment" {
  depends_on  = [aws_api_gateway_integration.my_get_integration]
  rest_api_id = aws_api_gateway_rest_api.my_api.id
#  stage_name  = "dev"
}


# Enable logging for the API Gateway stage
# Enable logging for the API Gateway stage
resource "aws_api_gateway_stage" "my_stage" {
  rest_api_id  = aws_api_gateway_rest_api.my_api.id
  stage_name   = "dev"

  deployment_id = aws_api_gateway_deployment.my_put_deployment.id

  access_log_settings {
    destination_arn = aws_cloudwatch_log_group.api_logs.arn
    format          = "$context.requestId $context.extendedRequestId"
  }

  lifecycle {
    ignore_changes = [deployment_id]  # Ignore changes to deployment_id
  }
}

# CloudWatch Log Group for API Gateway logs
resource "aws_cloudwatch_log_group" "api_logs" {
  name              = "/aws/api-gateway/my_api_logs"
  retention_in_days = 7
}

# Output the API Gateway endpoint
output "api_gateway_endpoint" {
  value = aws_api_gateway_deployment.my_put_deployment.invoke_url
}

here is my lambda function

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import boto3
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')
def lambda_handler(event, context):
operation = event['httpMethod']
if operation == 'POST':
item = json.loads(event['body'])
response = table.put_item(Item=item)
elif operation == 'GET':
item_id = event['queryStringParameters']['ID']
response = table.get_item(Key={'ID': item_id})
elif operation == 'PUT':
item = json.loads(event['body'])
response = table.update_item(Key={'ID': item['ID']}, UpdateExpression='SET attribute1 = :val1', ExpressionAttributeValues={':val1': item['attribute1']})
elif operation == 'DELETE':
item_id = event['queryStringParameters']['ID']
response = table.delete_item(Key={'ID': item_id})
return {
'statusCode': 200,
'body': json.dumps(response)
}
</code>
<code>import boto3 import json dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('MyTable') def lambda_handler(event, context): operation = event['httpMethod'] if operation == 'POST': item = json.loads(event['body']) response = table.put_item(Item=item) elif operation == 'GET': item_id = event['queryStringParameters']['ID'] response = table.get_item(Key={'ID': item_id}) elif operation == 'PUT': item = json.loads(event['body']) response = table.update_item(Key={'ID': item['ID']}, UpdateExpression='SET attribute1 = :val1', ExpressionAttributeValues={':val1': item['attribute1']}) elif operation == 'DELETE': item_id = event['queryStringParameters']['ID'] response = table.delete_item(Key={'ID': item_id}) return { 'statusCode': 200, 'body': json.dumps(response) } </code>
import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')

def lambda_handler(event, context):
    operation = event['httpMethod']
    if operation == 'POST':
        item = json.loads(event['body'])
        response = table.put_item(Item=item)
    elif operation == 'GET':
        item_id = event['queryStringParameters']['ID']
        response = table.get_item(Key={'ID': item_id})
    elif operation == 'PUT':
        item = json.loads(event['body'])
        response = table.update_item(Key={'ID': item['ID']}, UpdateExpression='SET attribute1 = :val1', ExpressionAttributeValues={':val1': item['attribute1']})
    elif operation == 'DELETE':
        item_id = event['queryStringParameters']['ID']
        response = table.delete_item(Key={'ID': item_id})
    return {
        'statusCode': 200,
        'body': json.dumps(response)
    }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật