Add a hit counter to our stack #
Okay, our hit counter is ready. Let’s use it in our app. Open cdk_workshop_stack.py
and add
the following highlighted code:
from constructs import Construct
from aws_cdk import (
Stack,
aws_lambda as _lambda,
aws_apigateway as apigw,
)
from .hitcounter import HitCounter
class CdkWorkshopStack(Stack):
def __init__(self, scope: Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# Defines an AWS Lambda resource
my_lambda = _lambda.Function(
self, 'HelloHandler',
runtime=_lambda.Runtime.PYTHON_3_7,
code=_lambda.Code.from_asset('lambda'),
handler='hello.handler',
)
hello_with_counter = HitCounter(
self, 'HelloHitCounter',
downstream=my_lambda,
)
apigw.LambdaRestApi(
self, 'Endpoint',
handler=hello_with_counter.handler,
)
Notice that we changed our API Gateway handler to hello_with_counter._handler
instead of my_lambda
. This basically means that whenever our endpoint is hit, API
Gateway will route the request to our hit counter handler, which will log the
hit and relay it over to the my_lambda
function. Then, the responses will be
relayed back in the reverse order all the way to the user.
Deploy #
cdk deploy
It might take a little while.
And the output:
cdkworkshop.Endpoint8024A810 = https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/
Test #
Okay, ready to give this a go? (you should, again, see the URL of your API in the output of the “deploy” command).
Use curl
or your web browser to hit your endpoint (we use -i
to show HTTP
response fields and status code):
curl -i https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/
Oh no… seems like something went wrong:
HTTP/1.1 502 Bad Gateway
...
{"message": "Internal server error"}
Let’s see how to find out what happened and fix it.