Here's a complete implementation of a REST API with API Gateway and Lambda using AWS CDK and Python:
Project Structure
code Copy code
my-api/
├── app.py
├── requirements.txt
├── lambda/
│ ├── __init__.py
│ ├── main.py
│ ├── handlers/
│ │ ├── __init__.py
│ │ ├── get_test.py
│ │ └── post_test.py
│ └── utils/
│ ├── __init__.py
│ └── response.py
└── cdk.json
1. Infrastructure Code (app.py)
python Copy code
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 RestApiStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# Create Lambda function
lambda_function = _lambda.Function(
self, "ApiHandler",
runtime=_lambda.Runtime.PYTHON_3_12,
handler="lambda/main.handler",
code=_lambda.Code.from_asset("lambda"),
timeout=Duration.seconds(30),
memory_size=128,
environment={
"POWERTOOLS_SERVICE_NAME": "rest-api-service",
"LOG_LEVEL": "INFO"
}
)
# Add AWS Lambda Powertools layer
powertools_layer = _lambda.LayerVersion.from_layer_version_arn(
self, "PowertoolsLayer",
layer_version_arn=f"arn:aws:lambda:{self.region}:017000801446:layer:AWSLambdaPowertoolsPythonV2:59"
)
lambda_function.add_layers(powertools_layer)
# Create API Gateway REST API
api = apigateway.RestApi(
self, "TestApi",
rest_api_name="Test Service",
description="This service serves test 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", "X-Amz-Security-Token"]
),
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")
# Add GET method
test_resource.add_method(
"GET",
apigateway.LambdaIntegration(lambda_function),
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",
apigateway.LambdaIntegration(lambda_function),
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 URL
CfnOutput(
self, "ApiEndpoint",
value=f"{api.url}test",
description="API endpoint URL"
)
# Create the app and stack
from aws_cdk import App
app = App()
RestApiStack(app, "RestApiStack")
app.synth()
2. Lambda Handler - Main Entry Point (lambda/main.py)
python Copy code
import json
import logging
from typing import Dict, Any
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
from lambda.handlers.get_test import handle_get_test
from lambda.handlers.post_test import handle_post_test
from lambda.utils.response import create_response
# Initialize Powertools
logger = Logger()
tracer = Tracer()
app = APIGatewayRestResolver()
@app.get("/test")
@tracer.capture_method
def get_test_handler():
"""Handle GET /test requests"""
try:
logger.info("Processing GET /test request")
return handle_get_test()
except Exception as e:
logger.error(f"Error processing GET request: {str(e)}")
return create_response(500, {"error": "Internal server error"})
@app.post("/test")
@tracer.capture_method
def post_test_handler():
"""Handle POST /test requests"""
try:
logger.info("Processing POST /test request")
# Get request body from the event
body = app.current_event.json_body if app.current_event.body else {}
return handle_post_test(body)
except Exception as e:
logger.error(f"Error processing POST request: {str(e)}")
return create_response(500, {"error": "Internal server error"})
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
def handler(event: dict, context: LambdaContext) -> dict:
"""Main Lambda handler function"""
logger.info("Lambda function invoked", extra={"event": event})
try:
# Process the request using the event handler
return app.resolve(event, context)
except Exception as e:
logger.exception("Unhandled exception in Lambda handler")
return create_response(500, {"error": "Internal server error"})
3. GET Handler (lambda/handlers/get_test.py)
python Copy code
from aws_lambda_powertools import Logger
from lambda.utils.response import create_response
logger = Logger()
def handle_get_test():
"""
Handle GET /test requests
Returns:
dict: API Gateway response format
"""
logger.info("Executing GET /test handler")
response_body = {
"message": "GET request successful",
"method": "GET",
"timestamp": __import__('datetime').datetime.utcnow().isoformat() + "Z"
}
logger.info("GET request processed successfully")
return create_response(200, response_body)
4. POST Handler (lambda/handlers/post_test.py)
python Copy code
from aws_lambda_powertools import Logger
from lambda.utils.response import create_response
logger = Logger()
def handle_post_test(body: dict):
"""
Handle POST /test requests
Args:
body (dict): Request body
Returns:
dict: API Gateway response format
"""
logger.info("Executing POST /test handler", extra={"request_body": body})
# Validate request body
if not isinstance(body, dict):
logger.warning("Invalid request body format")
return create_response(400, {"error": "Invalid request body format"})
response_body = {
"message": "POST request successful",
"method": "POST",
"received_data": body,
"timestamp": __import__('datetime').datetime.utcnow().isoformat() + "Z"
}
logger.info("POST request processed successfully")
return create_response(200, response_body)
5. Response Utility (lambda/utils/response.py)
python Copy code
from typing import Dict, Any
def create_response(status_code: int, body: Dict[str, Any]) -> Dict[str, Any]:
"""
Create a standardized API Gateway response
Args:
status_code (int): HTTP status code
body (dict): Response body
Returns:
dict: API Gateway response format
"""
return {
"statusCode": status_code,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS"
},
"body": __import__('json').dumps(body, default=str)
}
6. Requirements (requirements.txt)
txt Copy code
aws-cdk-lib==2.130.0
constructs>=10.0.0,<11.0.0
aws-lambda-powertools==2.33.1
7. CDK Configuration (cdk.json)
json Copy code
{
"app": "python3 app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__init__.py",
"python/__pycache__",
"tests"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn",
"aws-us-gov"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true
}
}
8. Init Files
lambda/init .py
python Copy code
# Empty init file
lambda/handlers/init .py
python Copy code
# Empty init file
lambda/utils/init .py
python Copy code
# Empty init file
Deployment Instructions
Install dependencies:
bash Copy code
pip install -r requirements.txt
Bootstrap CDK (if not already done):
bash Copy code
cdk bootstrap
Deploy the stack:
Testing the API
After deployment, you'll get an API endpoint URL. Test it with:
GET Request:
bash Copy code
curl -X GET https://your-api-gateway-url/test
POST Request:
bash Copy code
curl -X POST https://your-api-gateway-url/test \
-H "Content-Type: application/json" \
-d '{"message": "Hello World"}'
Key Features Implemented
Modular Architecture : Separate modules for routing, handlers, and utilities
AWS Lambda Powertools : For structured logging, tracing, and metrics
Proper Error Handling : Centralized error handling with appropriate logging
CORS Support : Proper CORS configuration for web applications
Type Hints : Full type annotations for better code maintainability
Structured Logging : JSON structured logging with correlation IDs
X-Ray Tracing : Distributed tracing enabled
Security Best Practices : Proper IAM permissions and secure configurations
Standardized Responses : Consistent API response format
Modern CDK Constructs : Using the latest CDK patterns and practices
This implementation follows AWS best practices and provides a scalable, maintainable foundation for a REST API service.