Setup your AWS API Gateway with custom domain in 7 steps

If you know how to use S3 for static site hosting, you will find it pretty easier to setup a CloudFront distribution and map it as a CNAME to your custom domain. However, it requires more manual operations to use a custom domain for API Gateway. API Gateway requires that you use https, but the certificate that it uses is only valid for the default domain.

Let’s say we have an URL generated by API Gateway:

https://ab123456.execute-api.us-west-2.amazonaws.com/production

This is what we want:

https://api.yourdomain.com

To do this, we are going to use Let’s Encrypt to get a free SSL certificate to use with API Gateway.

Step 1 — Generate key for certificate

We are going to use Google’s acme CLI tools. First of all, we need to download it via the command:

go get -u github.com/google/acme

If you do not have Go in your computer, you can install it by brew install golang.

Validate the installation by:

~/go/bin/acme help

Step 2 — Activate Let’s Encrypt account

You first need to create an account with the following command:

acme reg -gen -accept mailto:username@domain.com

Validate the result by:

$ ls ~/.config/acme
account.json account.key

Step 3 — Generate a private key for certification

Since AWS API Gateway only supports 2048 bit RSA certs, we have to use OpenSSL to generate the private key:

openssl genrsa -out api.yourdomain.com.key 2048

Step 4 — Verify your domain ownership

It will generate a TXT record for DNS verification. Do not press the enter yet until the TXT record is propagated.

acme cert -k api.yourdomain.com.key -dns=true api.yourdomain.com

Copy the value from the above command to your DNS service by key: _acme-challenge.api.

It takes time for different DNS service to apply the changes. Google provides a tool for you to check whether your change is correctly propagated.

For the above example, we use the URL

https://dns.google.com/query?name=api.yourdomain.com&type=TXT&dnssec=true

to query. You can press the enter key when the change has applied. Otherwise, you will receive authentication fail error.

Validate the result by:

$ ls
api.yourdomain.com.crt api.yourdomain.com.key

If you want to renew the certification, just run:

acme cert -k api.yourdomain.com.key api.yourdomain.com

Step 5 — Apply the certification with AWS Certification Manager

Place the generated certification and private key to AWS Console. You can follow the official steps:

Step 6 — Distribute your API Gateway to CloudFront

We are going to obtain a CloudFront URL so that we can apply it using CNAME.

Simply follow the official steps:

This steps will take more than 30mins.

Step 7 — Activate your API domain

Finally, you can copy the generated CloudFront URL to CNAME to api. After DNS propagation, you can finally access your API via api.yourdomain.com.