Sub topic 17
Serving the API from a custom domain
Every HTTP API gets a default URL such as https://abc123.execute-api.us-east-1.amazonaws.com. That URL works, but clients should not depend on it. It exposes the API ID, it changes if you recreate the API, and it gives you no way to move traffic between APIs without breaking callers. A custom domain such as api.example.com solves these problems.
This chapter assumes you have deployed an HTTP API with SAM and understand stages. It also assumes you can use the AWS CLI and have a domain name you control, ideally in a Route 53 hosted zone.
The pieces involved
A custom domain setup has four parts:
- An ACM certificate for the domain name. It proves ownership and enables HTTPS.
- A custom domain name resource in API Gateway. It holds the certificate and the TLS settings.
- API mappings that connect the domain, or a path under it, to a specific API and stage.
- A DNS record that points your hostname at the API Gateway domain name.
Regional endpoints only
HTTP APIs support only regional custom domain endpoints. REST APIs also offer edge-optimized domains, which sit behind CloudFront. HTTP APIs do not. If you want CloudFront features such as caching or a WAF in front, you put your own CloudFront distribution in front of the API.
This regional model gives one rule that causes many failed deployments: the ACM certificate must be in the same Region as the API. A certificate in us-east-1 does not work for an API in eu-west-1. (The us-east-1 requirement applies to CloudFront, not to regional API Gateway domains.)
Requesting the certificate
Request a public certificate with DNS validation:
aws acm request-certificate \
--region us-east-1 \
--domain-name api.example.com \
--validation-method DNSACM returns a certificate ARN. It also gives you a CNAME record that you must create in your DNS zone. If the zone is in Route 53, the console can create the record with one click. Once ACM sees the record, the certificate status changes from PENDING_VALIDATION to ISSUED. You cannot attach a certificate to a domain until it is issued.
You can also request a wildcard certificate, such as *.example.com. It lets you serve many API hostnames from one certificate, but it covers only one label deep. It matches api.example.com and does not match v1.api.example.com.
Creating the domain with the CLI
The CLI route shows what each resource does. First create the domain name:
aws apigatewayv2 create-domain-name \
--domain-name api.example.com \
--domain-name-configurations \
CertificateArn=arn:aws:acm:us-east-1:111122223333:certificate/EXAMPLE,EndpointType=REGIONAL,SecurityPolicy=TLS_1_2Then map a stage to a path under the domain:
aws apigatewayv2 create-api-mapping \
--domain-name api.example.com \
--api-id abc123 \
--stage '$default' \
--api-mapping-key v1Finally, read the values that DNS needs:
aws apigatewayv2 get-domain-name \
--domain-name api.example.com \
--query 'DomainNameConfigurations[0].[ApiGatewayDomainName,HostedZoneId]'The first value is a name like d-abc123.execute-api.us-east-1.amazonaws.com. The second is the hosted zone ID of API Gateway's own zone. You need both for a Route 53 alias record.
API mappings and the stage name
The API mapping key is the path prefix on the custom domain. With the mapping above, these requests behave as follows:
| Request URL | Reaches |
|---|---|
| `https://api.example.com/v1/items/42` | API `abc123`, stage `$default`, route `GET /items/{id}` |
| `https://api.example.com/items/42` | No mapping, so a 404 from API Gateway |
The mapping key is stripped before route matching. Your route definitions stay GET /items/{id}, without /v1. This matters when you write handlers. event["rawPath"] contains the path the client sent, including the mapping key, so code that inspects rawPath directly will see /v1/items/42. Match on routeKey or pathParameters instead, as shown in the handler chapters.
The stage name does not appear in the URL once you use a custom domain. You choose which stage a mapping points at, so the $default stage and a named stage like prod look the same to clients.
You can leave the mapping key empty to serve an API at the root of the domain. Each combination of domain and key must be unique. You can map different APIs under different keys on one domain, for example /orders to one API and /billing to another. That lets several teams share a hostname.
Defining the domain in SAM
In a SAM template, the Domain property of AWS::Serverless::HttpApi creates the domain, the mapping, and optionally the Route 53 record.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
CertificateArn:
Type: String
HostedZoneId:
Type: String
Resources:
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
DisableExecuteApiEndpoint: true
Domain:
DomainName: api.example.com
CertificateArn: !Ref CertificateArn
EndpointConfiguration: REGIONAL
SecurityPolicy: TLS_1_2
BasePath:
- /v1
Route53:
HostedZoneId: !Ref HostedZoneId
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}
Method: GET
Outputs:
ApiUrl:
Value: https://api.example.com/v1SAM expands this into a domain name resource, an API mapping, and a Route 53 record set. The Route53 block works only when the hosted zone is in the same account. For a zone in another account or at another DNS provider, omit Route53 and create a CNAME record yourself that points at the ApiGatewayDomainName value.
Turning off the default endpoint
DisableExecuteApiEndpoint: true in the template above makes the execute-api URL return 403. This is worth doing once the custom domain works, for three reasons:
- Clients cannot bypass rules you attach to the custom domain, such as a WAF in front of your own CloudFront distribution.
- You have a single URL to monitor and document.
- Mutual TLS, if you enable it, cannot be bypassed.
Do not set this flag until you have tested the custom domain. If DNS or the mapping is wrong, you have no fallback URL for debugging.
DNS records and propagation
For Route 53, use an alias record of type A that targets the API Gateway domain name and its hosted zone ID. Alias records at the zone apex work, cost nothing per query, and follow the endpoint if its IP addresses change. A plain CNAME cannot sit at the zone apex, so use an alias there.
After creating the record, check resolution before testing the API:
dig +short api.example.com
curl -i https://api.example.com/v1/items/42New records usually resolve within minutes, but resolvers that cached a previous negative answer can take longer.
Common failures
- Certificate not found or in the wrong Region. The domain creation fails. Request the certificate in the API's Region.
- Certificate still pending. Stack creation waits or fails. Confirm the validation CNAME exists and the status is
ISSUED. {"message":"Not Found"}on the custom domain. There is usually no mapping for the path you called. Check the mapping key and that you are not repeating the stage name.- 403
Forbiddenon the custom domain. Check whether you also disabled the default endpoint and whether the mapping points at a stage that exists. - Browser CORS errors after the move. The browser's
Originis still your frontend's, but the API URL changed. ConfirmAllowOriginslists the frontend origin, not the API hostname. - Cannot delete the stack. The domain is still mapped or referenced by DNS. Remove the mappings and records first.
Exercise
Exercise
Your HTTP API has the route GET /items/{id} on the $default stage. It is mapped to api.example.com with the mapping key v2. A developer calls https://api.example.com/items/42 and gets a 404. What is wrong, and what URL should they call? Inside the Lambda handler, what value does event["rawPath"] have for the working call?
Show answer
The mapping key v2 is a required path prefix, and the call omitted it, so no mapping matched. The correct URL is https://api.example.com/v2/items/42. API Gateway removes the mapping key before route matching, so the route stays GET /items/{id}. However, rawPath in the event is /v2/items/42, because it holds the path the client sent. Handlers should match on routeKey or pathParameters instead.
Exercise
You deploy a stack in eu-west-1, using an ACM certificate you issued earlier in us-east-1, and domain creation fails. Why, and how do you fix it?
Show answer
HTTP API custom domains are regional, so the certificate must be in the same Region as the API. Request a new certificate in eu-west-1, validate it with DNS, wait for the status ISSUED, and pass its ARN to the stack.