Skip to content

Commit 6ad9961

Browse files
Adding build recipes section
1 parent 83aaf43 commit 6ad9961

File tree

7 files changed

+144
-10
lines changed

7 files changed

+144
-10
lines changed

docs/build_recipes.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -358,10 +358,10 @@ Optimized approach using Lambda Layers to separate dependencies from application
358358
--8<-- "examples/build_recipes/sam/with-layers/layers/dependencies/requirements.txt"
359359
```
360360

361-
=== "src/api/app_sam_layer.py"
361+
=== "src/app/app_sam_layer.py"
362362

363363
```python
364-
--8<-- "examples/build_recipes/sam/with-layers/src/api/app_sam_layer.py"
364+
--8<-- "examples/build_recipes/sam/with-layers/src/app/app_sam_layer.py"
365365
```
366366

367367
=== "src/worker/worker_sam_layer.py"
@@ -463,10 +463,10 @@ Multi-environment CDK setup with separate stacks, DynamoDB integration, and SQS
463463
--8<-- "examples/build_recipes/cdk/multi-stack/app_multi_stack.py"
464464
```
465465

466-
=== "src/api/api.py"
466+
=== "src/app/api.py"
467467

468468
```python
469-
--8<-- "examples/build_recipes/cdk/multi-stack/src/api/api.py"
469+
--8<-- "examples/build_recipes/cdk/multi-stack/src/app/api.py"
470470
```
471471

472472
=== "src/worker/worker.py"
@@ -521,10 +521,10 @@ Pants excels at managing complex projects with multiple Lambda functions that sh
521521
--8<-- "examples/build_recipes/pants/multi-target/BUILD"
522522
```
523523

524-
=== "api/handler.py"
524+
=== "app/handler.py"
525525

526526
```python
527-
--8<-- "examples/build_recipes/pants/multi-target/api/handler.py"
527+
--8<-- "examples/build_recipes/pants/multi-target/app/handler.py"
528528
```
529529

530530
=== "worker/workder_pants.py"

examples/build_recipes/cdk/multi-stack/src/app/__init__.py

Whitespace-only changes.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import os
2+
3+
import boto3
4+
5+
from aws_lambda_powertools import Logger, Metrics, Tracer
6+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
7+
from aws_lambda_powertools.logging import correlation_paths
8+
from aws_lambda_powertools.metrics import MetricUnit
9+
10+
logger = Logger()
11+
tracer = Tracer()
12+
metrics = Metrics()
13+
app = APIGatewayRestResolver()
14+
15+
# Initialize AWS clients
16+
dynamodb = boto3.resource("dynamodb")
17+
sqs = boto3.client("sqs")
18+
19+
table = dynamodb.Table(os.environ["TABLE_NAME"])
20+
queue_url = os.environ["QUEUE_URL"]
21+
22+
23+
@app.get("/health")
24+
def health_check():
25+
return {"status": "healthy", "service": "powertools-cdk-api"}
26+
27+
28+
@app.post("/tasks")
29+
@tracer.capture_method
30+
def create_task():
31+
task_data = app.current_event.json_body
32+
33+
# Store in DynamoDB
34+
table.put_item(Item={"pk": task_data["task_id"], "task_type": task_data["task_type"], "status": "pending"})
35+
36+
# Send to SQS for processing
37+
sqs.send_message(QueueUrl=queue_url, MessageBody=app.current_event.body)
38+
39+
metrics.add_metric(name="TaskCreated", unit=MetricUnit.Count, value=1)
40+
logger.info("Task created", extra={"task_id": task_data["task_id"]})
41+
42+
return {"message": "Task created successfully", "task_id": task_data["task_id"]}
43+
44+
45+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
46+
@tracer.capture_lambda_handler
47+
@metrics.log_metrics(capture_cold_start_metric=True)
48+
def lambda_handler(event, context):
49+
return app.resolve(event, context)

examples/build_recipes/cdk/multi-stack/stacks/powertools_cdk_stack.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,14 @@ def _create_api_function(self) -> _lambda.Function:
7373
self,
7474
"ApiFunction",
7575
runtime=_lambda.Runtime.PYTHON_3_13,
76-
handler="api.lambda_handler",
77-
code=_lambda.Code.from_asset("src/api"),
76+
handler="app.lambda_handler",
77+
code=_lambda.Code.from_asset("src/app"),
7878
layers=[self.powertools_layer],
7979
timeout=Duration.seconds(30),
8080
memory_size=512 if self.env == "prod" else 256,
8181
environment={
8282
"ENVIRONMENT": self.env,
83-
"POWERTOOLS_SERVICE_NAME": f"api-{self.env}",
83+
"POWERTOOLS_SERVICE_NAME": f"app-{self.env}",
8484
"POWERTOOLS_METRICS_NAMESPACE": f"MyApp/{self.env}",
8585
"POWERTOOLS_LOG_LEVEL": "INFO" if self.env == "prod" else "DEBUG",
8686
"TABLE_NAME": self.table.table_name,
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from aws_lambda_powertools import Logger, Metrics, Tracer
2+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
3+
from aws_lambda_powertools.logging import correlation_paths
4+
from aws_lambda_powertools.metrics import MetricUnit
5+
6+
logger = Logger()
7+
tracer = Tracer()
8+
metrics = Metrics()
9+
app = APIGatewayRestResolver()
10+
11+
12+
@app.get("/health")
13+
def health_check():
14+
return {"status": "healthy", "service": "powertools-pants-api"}
15+
16+
17+
@app.get("/metrics")
18+
def get_metrics():
19+
metrics.add_metric(name="MetricsEndpointCalled", unit=MetricUnit.Count, value=1)
20+
return {"message": "Metrics recorded"}
21+
22+
23+
@app.post("/tasks")
24+
def create_task():
25+
task_data = app.current_event.json_body
26+
logger.info("Task created", extra={"task": task_data})
27+
metrics.add_metric(name="TaskCreated", unit=MetricUnit.Count, value=1)
28+
return {"message": "Task created successfully", "task_id": task_data.get("id")}
29+
30+
31+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
32+
@tracer.capture_lambda_handler
33+
@metrics.log_metrics(capture_cold_start_metric=True)
34+
def lambda_handler(event, context):
35+
return app.resolve(event, context)
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import Optional
2+
3+
import requests
4+
from pydantic import BaseModel
5+
6+
from aws_lambda_powertools import Logger, Metrics, Tracer
7+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
8+
from aws_lambda_powertools.logging import correlation_paths
9+
from aws_lambda_powertools.metrics import MetricUnit
10+
11+
logger = Logger()
12+
tracer = Tracer()
13+
metrics = Metrics()
14+
app = APIGatewayRestResolver()
15+
16+
17+
class UserModel(BaseModel):
18+
name: str
19+
email: str
20+
age: Optional[int] = None
21+
22+
23+
@app.get("/health")
24+
def health_check():
25+
return {"status": "healthy", "service": "powertools-sam-layers"}
26+
27+
28+
@app.post("/users")
29+
def create_user(user: UserModel):
30+
logger.info("Creating user", extra={"user": user.model_dump()})
31+
metrics.add_metric(name="UserCreated", unit=MetricUnit.Count, value=1)
32+
return {"message": f"User {user.name} created successfully"}
33+
34+
35+
@app.get("/external")
36+
@tracer.capture_method
37+
def fetch_external_data():
38+
"""Example using requests from dependencies layer"""
39+
response = requests.get("https://httpbin.org/json")
40+
data = response.json()
41+
42+
metrics.add_metric(name="ExternalApiCalled", unit=MetricUnit.Count, value=1)
43+
return {"external_data": data}
44+
45+
46+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
47+
@tracer.capture_lambda_handler
48+
@metrics.log_metrics(capture_cold_start_metric=True)
49+
def lambda_handler(event, context):
50+
return app.resolve(event, context)

examples/build_recipes/sam/with-layers/template.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Resources:
2828
ApiFunction:
2929
Type: AWS::Serverless::Function
3030
Properties:
31-
CodeUri: src/api/
31+
CodeUri: src/app/
3232
Handler: app_sam_layer.lambda_handler
3333
Layers:
3434
- arn:aws:lambda:us-east-1:017000801446:layer:AWSLambdaPowertoolsPythonV3-python313-x86_64:21

0 commit comments

Comments
 (0)