Use the hit counter

Add a hit counter to our stack

Okay, our hit counter is ready. Let’s use it in our app. Open and add the following highlighted code:

from aws_cdk import (
    aws_lambda as _lambda,
    aws_apigateway as apigw,

from hitcounter import HitCounter

class CdkworkshopStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Defines an AWS Lambda resource
        my_lambda = _lambda.Function(
            self, 'HelloHandler',

        hello_with_counter = HitCounter(
            self, 'HelloHitCounter',

            self, 'Endpoint',

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.


cdk deploy

It might take a little while.

And the output:

cdkworkshop.Endpoint8024A810 =


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

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.