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 src/CdkWorkshop/CdkWorkshopStack.cs and add the following highlighted code:

using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.Lambda;

namespace CdkWorkshop
    public class CdkWorkshopStack : Stack
        public CdkWorkshopStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
            // Defines a new lambda resource
            var hello = new Function(this, "HelloHandler", new FunctionProps
                Runtime = Runtime.NODEJS_10_X, // execution environment
                Code = Code.FromAsset("lambda"), // Code loaded from the "lambda" directory
                Handler = "hello.handler" // file is "hello", function is "handler"

            var helloWithCounter = new HitCounter(this, "HelloHitCounter", new HitCounterProps
                Downstream = hello

            // defines an API Gateway REST API resource backed by our "hello" function.
            new LambdaRestApi(this, "Endpoint", new LambdaRestApiProps
                Handler = helloWithCounter.Handler

Notice that we changed our API Gateway handler to helloWithCounter.handler instead of hello. 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 hello 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:

CdkWorkshopStack.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.