CDK RestApi & Custom Domains

blockimperiumgames
2 min readAug 12, 2020

--

Creating custom domains for RestApis is the best way to make sure your API or system can easily be used by 3rd parties by ensuring that you can publish an endpoint that is non-changing and integrated with the rest of your web presence.

There are, however, a number of ways to do this in Amazon’s CDK and many approaches can take you down a road filled with peril — mostly because of some of the assumptions made in the documentation for the feature. To address this I’ll outline the CDK code that properly sets up a RestApi so you don’t have to go through any trial and error to get your RestApi working properly. Note, this approach is similar for proxy RestApis but it is not specifically covered here.

In this post, we will go from the well-engineered URIs that are generated by Amazon to something akin to:

https://api.example.com/basePath/{function}

First, define your API in your CDK Stack or construct.

Next, define the RestApi

In this particular example, I am setting the deployOptions so the stage is created when the API is created and I am explicitly setting the endpoint to type EDGE. If you’re creating a regional endpoint, you can set this to REGIONAL.

The next part may seem counterintuitive, but the API needs to be associated with a domain name or it will not publish. If you try to associate it with your subdomain instead of the domain, you will receive an error from CDK (“InternalError” or similar).

In this particular example, we’re adding a domain named the same as the domain name that we’re using and setting the certificate (example.com). The above pieces are necessary for your API to just be happily published.

Next, we need to deal with the DomainName for the custom domain.

Note here that the custom domain is being set with a subdomainPrefix. If you’re doing api.example.com, the subdomainPrefix would be “api” in that case.

To this domain, we will add the base path mapping that we desire. Since basePath mappings should not contain uppercase letters or special characters we strip those out here.

The last step is to create an A record that is pointed at this domain. Without this step, none of the other steps amount to much:

Once you’ve create this ARecord, you will see in the Custom Domains interface in API Gateway that there is a mapping that points to the API that you just created at the subdomainPrefix and the basepath:

https://api.example.com/basePath

Hopefully this saves someone some time. This code was all tested and shown to work with the latest version of the CDK 1.57

--

--

Responses (5)