How can I declare the $default catch-all route using CDK for an API Gateway?

Viewed 290

Within the AWS console, it is possible to add a route to an API Gateway with the value of $default. This then removes the ability to input a HTTP method for the route.

The AWS console describes it as: "You can also specify one $default route per API. The $default route is invoked when the request to the API matches no other routes."

I am trying to recreate this using AWS CDK v2 (C# in this case) however am having no luck. I integrate my API Gateway with a Lambda function based on an image stored in ECR, unfortunately I cannot get my API Gateway to be created with the $default route.

httpApi.AddRoutes(new AddRoutesOptions()
{
   Path = "$default",
   Integration = lambdaProxyIntegration
});

Doing the above, defaults the HTTP method to POST. It is also possible to specify a HTTP method like so:

httpApi.AddRoutes(new AddRoutesOptions()
{
   Path = "$default",
   Integration = lambdaProxyIntegration,
   Methods = new [] {HttpMethod.ANY}
});

But there is no option equivalent to when you enter $default within the AWS console & it greys out the drop down to select a Http Method.

Any ideas?

Thanks

1 Answers

Solved the problem.

So confusingly, despite the $default catch-all route, being a route. You don't actually specify it using the AddRoutes() method. The clue is in the fact that it takes an enum called HttpMethod.

Instead, a $default route is applied automatically when you set the DefaultIntegration attribute on the HttpApiProps object of your HttpApi.

So in my case, httpApi from the examples in the question were an instance of the HttpApi class.

var httpApi = new HttpApi(this, Constants.API_GATEWAY_ID, new HttpApiProps()
{
   ApiName = "Your API name",
   CreateDefaultStage = true,
   DefaultIntegration = lambdaProxyIntegration
});

Once you specify the DefaultIntegration, AWS will set the $default route as expected.

Related