from aws_cdk import (
Stack,
aws_apigateway as apigateway,
aws_lambda as _lambda,
aws_iam as iam,
Duration,
CfnOutput
)
from constructs import Construct
import os
class ApiStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# Create Lambda function with best practices
api_lambda = _lambda.Function(
self, "ApiFunction",
runtime=_lambda.Runtime.PYTHON_3_11,
handler="lambda/main.handler",
code=_lambda.Code.from_asset("lambda"),
timeout=Duration.seconds(30),
memory_size=128,
environment={
"POWERTOOLS_SERVICE_NAME": "api-service",
"POWERTOOLS_LOG_LEVEL": "INFO",
"POWERTOOLS_LOGGER_SAMPLE_RATE": "0.1"
}
)
# Add CloudWatch Logs permissions
api_lambda.add_to_role_policy(
iam.PolicyStatement(
actions=[
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
resources=["*"]
)
)
# Create API Gateway REST API
api = apigateway.RestApi(
self, "ApiGateway",
rest_api_name="TestApi",
description="Test API with GET and POST endpoints",
default_cors_preflight_options=apigateway.CorsOptions(
allow_origins=apigateway.Cors.ALL_ORIGINS,
allow_methods=apigateway.Cors.ALL_METHODS,
allow_headers=["Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key"]
),
deploy_options=apigateway.StageOptions(
stage_name="prod",
logging_level=apigateway.MethodLoggingLevel.INFO,
data_trace_enabled=True,
metrics_enabled=True
)
)
# Create /test resource
test_resource = api.root.add_resource("test")
# Create Lambda integration
lambda_integration = apigateway.LambdaIntegration(
api_lambda,
proxy=True,
integration_responses=[
apigateway.IntegrationResponse(
status_code="200",
response_parameters={
"method.response.header.Access-Control-Allow-Origin": "'*'"
}
)
]
)
# Add GET method
test_resource.add_method(
"GET",
lambda_integration,
method_responses=[
apigateway.MethodResponse(
status_code="200",
response_parameters={
"method.response.header.Access-Control-Allow-Origin": True
}
)
]
)
# Add POST method
test_resource.add_method(
"POST",
lambda_integration,
method_responses=[
apigateway.MethodResponse(
status_code="200",
response_parameters={
"method.response.header.Access-Control-Allow-Origin": True
}
)
]
)
# Add OPTIONS method for CORS
test_resource.add_method(
"OPTIONS",
apigateway.MockIntegration(
integration_responses=[
apigateway.IntegrationResponse(
status_code="200",
response_parameters={
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'",
"method.response.header.Access-Control-Allow-Origin": "'*'",
"method.response.header.Access-Control-Allow-Methods": "'GET,POST,OPTIONS'"
}
)
],
passthrough_behavior=apigateway.PassthroughBehavior.NEVER,
request_templates={
"application/json": "{\"statusCode\": 200}"
}
),
method_responses=[
apigateway.MethodResponse(
status_code="200",
response_parameters={
"method.response.header.Access-Control-Allow-Headers": True,
"method.response.header.Access-Control-Allow-Methods": True,
"method.response.header.Access-Control-Allow-Origin": True
}
)
]
)
# Output the API endpoint
CfnOutput(
self, "ApiEndpoint",
value=f"{api.url}test",
description="API Gateway endpoint URL"
)