

# Publish REST APIs for customers to invoke
Publish

Simply creating and developing an API Gateway API doesn't automatically make it callable by your users. To make it callable, you must deploy your API to a stage. In addition, you might want to customize the URL that your users will use to access your API. You can give it a domain that is consistent with your brand or is more memorable than the default URL for your API.

In this section, you can learn how to deploy your API and customize the URL that you provide to users to access it. 

**Note**  
To augment the security of your API Gateway APIs, the `execute-api.{region}.amazonaws.com` domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/). For further security, we recommend that you use cookies with a `__Host-` prefix if you ever need to set sensitive cookies in the default domain name for your API Gateway APIs. This practice will help to defend your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

**Topics**
+ [

# Deploy REST APIs in API Gateway
](how-to-deploy-api.md)
+ [

# Custom domain name for public REST APIs in API Gateway
](how-to-custom-domains.md)

# Deploy REST APIs in API Gateway
Deploy REST APIs

 After creating your API, you must deploy it to make it callable by your users. 

To deploy an API, you create an API deployment and associate it with a stage. A stage is a logical reference to a lifecycle state of your API (for example, `dev`, `prod`, `beta`, `v2`). API stages are identified by the API ID and stage name. They're included in the URL that you use to invoke the API. Each stage is a named reference to a deployment of the API and is made available for client applications to call. 

**Important**  
Every time you update an API, you must redeploy the API to an existing stage or to a new stage. Updating an API includes modifying routes, methods, integrations, authorizers, resource policies, and anything else other than stage settings. 

As your API evolves, you can continue to deploy it to different stages as different versions of the API. You can also deploy your API updates as a [canary release deployment](canary-release.md). This enables your API clients to access, on the same stage, the production version through the production release, and the updated version through the canary release. 

To call a deployed API, the client submits a request against an API's URL. The URL is determined by an API's protocol (HTTP(S) or (WSS)), hostname, stage name, and (for REST APIs) resource path. The hostname and the stage name determine the API's base URL. 

Using the API's default domain name, the base URL of a REST API (for example) in a given stage (`{stageName}`) is in the following format:

```
https://{restapi-id}.execute-api.{region}.amazonaws.com/{stageName}
```

 To make the API's default base URL more user-friendly, you can create a custom domain name (for example, `api.example.com`) to replace the default hostname of the API. To support multiple APIs under the custom domain name, you must map an API stage to a base path. 

With a custom domain name of `{api.example.com}` and the API stage mapped to a base path of (`{basePath}`) under the custom domain name, the base URL of a REST API becomes the following: 

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

 For each stage, you can optimize API performance by adjusting the default account-level request throttling limits and enabling API caching. You can also enable logging for API calls to CloudTrail or CloudWatch, and can select a client certificate for the backend to authenticate the API requests. In addition, you can override stage-level settings for individual methods and define stage variables to pass stage-specific environment contexts to the API integration at runtime. 

Stages enable robust version control of your API. For example, you can deploy an API to a `test` stage and a `prod` stage, and use the `test` stage as a test build and use the `prod` stage as a stable build. After the updates pass the test, you can promote the `test` stage to the `prod` stage. The promotion can be done by redeploying the API to the `prod` stage or updating a stage variable value from the stage name of `test` to that of `prod`.

 In this section, we discuss how to deploy an API by using the [API Gateway console](https://console.amazonaws.cn/apigateway) or calling the [API Gateway REST API](https://docs.amazonaws.cn/apigateway/latest/api/). To use other tools, see the documentation of the [Amazon CLI](https://docs.amazonaws.cn/cli/latest/reference/apigateway/) or an [Amazon SDK](https://aws.amazon.com/developer/tools/#sdk). 

**Topics**
+ [

# Create a deployment for a REST API in API Gateway
](set-up-deployments.md)
+ [

# Set up a stage for a REST API in API Gateway
](set-up-stages.md)
+ [

# Set up an API Gateway canary release deployment
](canary-release.md)
+ [

# Updates to REST APIs that require redeployment
](updating-api.md)

# Create a deployment for a REST API in API Gateway
Create a deployment

 In API Gateway, a REST API deployment is represented by a [Deployment](https://docs.amazonaws.cn/apigateway/latest/api/API_Deployment.html) resource. It's similar to an executable of an API that is represented by a [RestApi](https://docs.amazonaws.cn/apigateway/latest/api/API_RestApi.html) resource. 

For the client to call your API, you must create a deployment and associate a stage with it. A stage is represented by a [Stage](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html) resource. It represents a snapshot of the API, including methods, integrations, models, mapping templates, and Lambda authorizers (formerly known as custom authorizers). When you update the API, you can redeploy the API by associating a new stage with the existing deployment. We discuss creating a stage in [Set up a stage for a REST API in API Gateway](set-up-stages.md).

**Topics**
+ [

## Create a deployment
](#create-deployment)
+ [

## Next steps for your API deployment
](#apigateway-deployment-next-steps)

## Create a deployment


The following procedures show how to create a deployment for a REST API.

------
#### [ Amazon Web Services Management Console ]

 You must have created a REST API before deploying it for the first time. For more information, see [Develop REST APIs in API Gateway](rest-api-develop.md). 

 The API Gateway console lets you deploy an API by creating a deployment and associating it with a new or existing stage. 

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1.  In the **APIs** navigation pane, choose the API you want to deploy. 

1. In the **Resources** pane, choose **Deploy API**.

1. For **Stage**, select from the following:

   1. To create a new stage, select **New stage**, and then enter a name in **Stage name**. Optionally, you can provide a description for the deployment in **Deployment description**.

   1. To choose an existing stage, select the stage name from the dropdown menu. You might want to provide a description of the new deployment in **Deployment description**.

   1. To create a deployment that is not associated with a stage, select **No stage**. Later, you can associate this deployment with a stage.

1. Choose **Deploy**.

------
#### [ Amazon CLI ]

When you create a deployment, you instantiate the [Deployment](https://docs.amazonaws.cn/apigateway/latest/api/API_Deployment.html) resource.

The following [create-deployment](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-deployment.html) command creates a new deployment:

```
 aws apigateway create-deployment --rest-api-id rest-api-id
```

You can't call the API until you associate this deployment with a stage. With an existing stage, you can do this by updating the stage's [deploymentId](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#deploymentId) property with the newly created deployment ID. The following [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command updates the stage with a new deployment. In the console, this is called the **Active deployment**.

```
 aws apigateway update-stage \
    --rest-api-id rest-api-id \ 
    --stage-name 'stage-name' \ 
    --patch-operations op='replace',path='/deploymentId',value='deployment-id'
```

When you create your deployment, you can also associate it with a new stage at the same time. The following [create-deployment](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-deployment.html) command creates a new deployment and associates it with a new stage called `beta`:

```
 aws apigateway create-deployment \
    --rest-api-id rest-api-id \
    --stage-name beta
```

------

To redeploy an API, perform the same steps. You can reuse the same stage.

## Next steps for your API deployment


The following are next steps for your API deployment.

Modify stage settings  
After an API is deployed, you can modify the stage settings to enable or disable the API cache, logging, or request throttling. You can also choose a client certificate for the backend to authenticate API Gateway and set stage variables to pass deployment context to the API integration at runtime. For more information, see [Modify stage settings](set-up-stages.md#how-to-stage-settings)  
After modifying stage settings, you must redeploy the API for the changes to take effect.  
 If the updated settings, such as enabling logging, requires a new IAM role, you can add the required IAM role without redeploying the API. However, it might take a few minutes before the new IAM role takes effect. Before that happens, traces of your API calls are not logged even if you have enabled the logging option. 

Choose different deployment-stage combinations  
 Because a deployment represents an API snapshot and a stage defines a path into a snapshot, you can choose different deployment-stage combinations to control how users call into different versions of the API. This is useful, for example, when you want to roll back API state to a previous deployment or to merge a 'private branch' of the API into the public one.   
 The following procedure shows how to do this using the **Stage Editor** in the API Gateway console. It is assumed that you must have deployed an API more than once.   

1. If you're not already on the **Stages** pane, in the main navigation pane, choose **Stages**.

1. Select the stage you want to update.

1. On the **Deployment history** tab, select the deployment you want the stage to use. 

1. Choose **Change active deployment**.

1. Confirm you want to change the active deployment and choose **Change active deployment** in the **Make active deployment** dialog box.

Pass deployment-specific data to your API.  
 For a deployment, you can set or modify stage variables to pass deployment-specific data to the API integration at runtime. You can do this on the **Stage Variables** tab in the **Stage Editor**. For more information, see instructions in [Use stage variables for a REST API in API Gateway](stage-variables.md).

# Set up a stage for a REST API in API Gateway
Set up a stage

A stage is a named reference to a deployment, which is a snapshot of the API. You use a [Stage](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html) to manage and optimize a particular deployment. For example, you can configure stage settings to enable caching, customize request throttling, configure logging, define stage variables, or attach a canary release for testing. The following section shows how to create and configure your stage.

## Create a new stage


 After the initial deployment, you can add more stages and associate them with existing deployments. You can use the API Gateway console to create a new stage, or you can choose an existing stage while deploying an API. In general, you can add a new stage to an API deployment before redeploying the API. To create a new stage using the API Gateway console, follow these steps: 

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a REST API.

1. In the main navigation pane, choose **Stages** under an API.

1. From the **Stages** navigation pane, choose **Create stage**.

1.  For **Stage name**, enter a name, for example, **prod**. 
**Note**  
Stage names can only contain alphanumeric characters, hyphens, and underscores. Maximum length is 128 characters.

1.  (Optional). For **Description**, enter a stage description.

1. For **Deployment**, select the date and time of the existing API deployment you want to associate with this stage.

1. Under **Additional settings**, you can specify additional settings for your stage.

1. Choose **Create stage**.

## Modify stage settings
Update stage settings

After a successful deployment of an API, the stage is populated with default settings. You can use the console or the API Gateway REST API to change the stage settings, including API caching and logging. If you've modified the default endpoint of your REST API, when you update a stage, the modification is propagated to all stages of your API. The following steps show you how to do so using the **Stage editor** of the API Gateway console.

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a REST API.

1. In the main navigation pane, choose **Stages** under an API.

1. In the **Stages** pane, choose the name of the stage.

1. In the **Stage details** section, choose **Edit**.

1. (Optional) For **Stage description**, edit the description.

1. For **Additional settings**, you modify the following settings:

     
**Cache settings**  
To enable API caching for the stage, turn on **Provision API cache**. Then configure the **Default method-level caching**, **Cache capacity**, **Encrypt cache data**, **Cache time-to-live (TTL)**, as well as any requirements for per-key cache invalidation.  
Caching is not active until you turn on the default method-level caching or turn on the method-level cache for a specific method.  
For more information about cache settings, see [Cache settings for REST APIs in API Gateway](api-gateway-caching.md).  
If you enable API caching for an API stage, your Amazon account might be charged for API caching. Caching isn't eligible for the Amazon Free Tier.  
**Throttling settings**  
To set stage-level throttling targets for all of the methods associated with this API, turn on **Throttling**.  
For **Rate**, enter a target rate. This is the rate, in requests per second, that tokens are added to the token bucket. The stage-level rate must not be more than the [account-level](api-gateway-request-throttling.md#apig-request-throttling-account-level-limits) rate as specified in [Quotas for configuring and running a REST API in API Gateway](api-gateway-execution-service-limits-table.md).   
For **Burst**, enter a target burst rate. The burst rate, is the capacity of the token bucket. This allows more requests through for a period of time than the target rate. This stage-level burst rate must not be more than the [account-level](api-gateway-request-throttling.md#apig-request-throttling-account-level-limits) burst rate as specified in [Quotas for configuring and running a REST API in API Gateway](api-gateway-execution-service-limits-table.md).   
Throttling rates are not hard limits, and are applied on a best-effort basis. In some cases, clients can exceed the targets that you set. Don’t rely on throttling to control costs or block access to an API. Consider using [Amazon Budgets](https://docs.amazonaws.cn/cost-management/latest/userguide/budgets-managing-costs.html) to monitor costs and [Amazon WAF](https://docs.amazonaws.cn/waf/latest/developerguide/waf-chapter.html) to manage API requests.  
**Firewall and certificate settings**  
To associate an Amazon WAF web ACL with the stage, select a web ACL from the **Web ACL** dropdown list. If desired, choose **Block API Request if WebACL cannot be evaluated (Fail- Close)**.  
To select a client certificate for your stage, select a certificate from the **Client certificate** dropdown menu.

1. Choose **Continue**.

1. Review your changes and choose **Save changes**.

1. To enable Amazon CloudWatch Logs for all of the methods associated with this stage of this API Gateway API, in the **Logs and tracing** section, choose **Edit**.
**Note**  
To enable CloudWatch Logs, you must also specify the ARN of an IAM role that enables API Gateway to write information to CloudWatch Logs on behalf of your user. To do so, choose **Settings** from the **APIs** main navigation pane. Then, for **CloudWatch log role**, enter the ARN of an IAM role.   
For common application scenarios, the IAM role could attach the managed policy of [AmazonAPIGatewayPushToCloudWatchLogs](https://docs.amazonaws.cn/aws-managed-policy/latest/reference/AmazonAPIGatewayPushToCloudWatchLogs.html).  
The IAM role must also contain the following trust relationship statement:  

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "",
         "Effect": "Allow",
         "Principal": {
           "Service": "apigateway.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```
  
For more information about CloudWatch, see the *[Amazon CloudWatch User Guide](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)*.

1. Select a logging level from the **CloudWatch Logs** dropdown menu. The logging levels are the following:
   + **Off** – Logging is not turned on for this stage. 
   + **Errors only** – Logging is enabled for errors only. 
   + **Errors and info logs** – Logging is enabled for all events.

1. Select **Data tracing** to have API Gateway report to CloudWatch the data trace logging for your stage. This can be useful to troubleshoot APIs, but can result in logging sensitive data.
**Note**  
We recommend that you don't use **Data tracing** for production APIs.

1. Select **Detailed metrics** to have API Gateway report to CloudWatch the API metrics of `API calls`, `Latency`, `Integration latency`, `400 errors`, and `500 errors`. For more information about CloudWatch, see the [Basic monitoring and detailed monitoring](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/cloudwatch-metrics-basic-detailed.html) in the Amazon CloudWatch User Guide.
**Important**  
Your account is charged for accessing method-level CloudWatch metrics, but not the API-level or stage-level metrics.

1. To enable access logging to a destination, turn on **Custom access logging**.

1. For **Access log destination ARN**, enter the ARN of a log group or a Firehose stream. 

   The ARN format for Firehose is `arn:aws:firehose:{region}:{account-id}:deliverystream/amazon-apigateway-{your-stream-name}`. The name of your Firehose stream must be `amazon-apigateway-{your-stream-name}`.

1. In **Log format**, enter a log format. To learn more about example log formats, see [CloudWatch log formats for API Gateway](set-up-logging.md#apigateway-cloudwatch-log-formats).

1. To enable [Amazon X-Ray](https://docs.amazonaws.cn/xray/latest/devguide/xray-services-apigateway.html) tracing for the API stage, select ** X-Ray tracing**. For more information, see [Trace user requests to REST APIs using X-Ray in API Gateway](apigateway-xray.md).

1. Choose **Save changes**. Redeploy your API for the new settings to take effect.

## Override stage-level settings


After you customize the stage-level settings, you can override them for each API method. Some of these options might result in additional charges to your Amazon Web Services account.

1. To configure method overrides, expand the stage under the secondary navigation pane, and then choose a method.

1. For **Method overrides**, choose **Edit**.

1. To turn on method-level CloudWatch settings, for **CloudWatch Logs**, select a logging level.

1. To turn on data trace logging for your method, select **Data tracing**.
**Note**  
We recommend that you don't use **Data tracing** for production APIs.

1. To turn on method-level detailed metrics, select **Detailed metrics**. Your account is charged for accessing method-level CloudWatch metrics, but not the API-level or stage-level metrics.

1. To turn on method-level throttling, select **Throttling**. Enter the appropriate method-level options. To learn more about throttling, see [Throttle requests to your REST APIs for better throughput in API Gateway](api-gateway-request-throttling.md).

1. To configure the method-level cache, select **Enable method cache**. If you change the default method-level caching setting in the **Stage details**, it doesn't affect this setting.

1. Choose **Save**.

# Add an API Gateway REST API as a target for Amazon Bedrock AgentCore Gateway
Add a stage to an Amazon Bedrock AgentCore Gateway

An Amazon Bedrock AgentCore Gateway provides AI agent developers a secure way to expose your API Gateway REST APIs as Model Context Protocol (MCP)-compatible tools. AgentCore Gateway uses targets to define tools. When you add your stage as a target, your Gateway becomes a single MCP URL that enables access to the tools for an agent. For more information, see [API Gateway REST API stages as targets](https://docs.amazonaws.cn/bedrock-agentcore/latest/devguide/gateway-target-api-gateway.html) in the *Amazon Bedrock AgentCore Gateway Developer Guide*.

API Gateway targets connect your AgentCore Gateway to stages of your REST APIs. You can include the entire stage as a target, or select resources. After you create the API Gateway target, AgentCore Gateway translates incoming MCP requests into HTTP requests and handles the response formatting. MCP clients can retrieve API documentation using the `tools/list` method and invoke APIs using the `tools/call` method.

## Considerations


The following considerations might impact your use adding a stage as a target to a AgentCore Gateway:
+ You must already have a AgentCore Gateway.
+ Only public REST APIs are supported.
+ The default endpoint of your API cannot be disabled.
+ Every method of your API must either have an [operation name](https://docs.amazonaws.cn/apigateway/latest/api/API_PutMethod.html#apigw-PutMethod-request-operationName) defined for it, or your need to create a name override when you add your stage as a target. This name is used as the tool name that agents use to interact with your method.
+ You can use `API_KEY`, `NO_AUTH`, or `GATEWAY_IAM_ROLE` credential provider types for Outbound Auth to allow your Gateway to access your API. The `API_KEY` credential provider is defined by AgentCore Gateway. You can use your existing API Gateway API key. For more information, see [Setting up Outbound Auth](https://docs.amazonaws.cn/bedrock-agentcore/latest/devguide/gateway-outbound-auth.html).
+ If you use a Amazon Cognito user pool or Lambda authorizer to control access to your API, MCP clients cannot access it.
+ Your API must be in the same account and Region as your AgentCore Gateway.

## Add a stage of an API as a target for a AgentCore Gateway


The following procedure shows how to add a stage of an API as a target for a AgentCore Gateway.

**To add a stage of an API as a target for a AgentCore Gateway**

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a REST API that's deployed to a stage.

1. In the main navigation pane, choose **Stages**.

1. Choose **Stage actions**, and then choose **Create MCP target**.

1. For **AgentCore Gateway**, select an AgentCore Gateway.

1. For **Target name**, enter a target name.

1. For **Target description**, enter a description.

1. Keep the provided API and stage.

1. For **Select API resources**, select the resources of your API that agents using your AgentCore Gateway can access.

   If you don't select a resource, an agent cannot view the documentation or invoke the endpoint. 

1. The combination of the resource and the method are the operations for the tool. If your operation does not have a name, create a name override.

   You can also define an operation name for a method when you create it.

1. For **Outbound Auth configuration**, choose either **IAM Role **, **No authorization** or **API key**.

1. Choose **Create target**.

To view all the AgentCore Gateways that have access to your APIs, choose the **MCP targets** section in the main navigation pane. In this section, you can create a MCP target for any API in your Region deployed to a stage. Choose **Create MCP target** and follow the previous steps.

You can also view the available tools for your target and edit your target in the AgentCore Gateway console. For more information, see [Add targets to an existing AgentCore Gateway](https://docs.amazonaws.cn/bedrock-agentcore/latest/devguide/gateway-building-adding-targets.html).

# Delete a stage
Delete a stage

When you no longer need a stage, you can delete it to avoid paying for unused resources. The following steps show you how to use the API Gateway console to delete a stage.

**Warning**  
 Deleting a stage might cause part or all of the corresponding API to be unusable by API callers. Deleting a stage cannot be undone, but you can recreate the stage and associate it with the same deployment. 

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a REST API.

1. In the main navigation pane, choose **Stages**.

1. In the **Stages** pane, choose the stage you want to delete, and then choose **Stage actions**, **Delete stage**.

1. When you're prompted, enter **confirm**, and then choose **Delete**.

# Set up tags for an API stage in API Gateway
Set up tags

In API Gateway, you can add a tag to an API stage, remove the tag from the stage, or view the tag. To do this, you can use the API Gateway console, the Amazon CLI/SDK, or the API Gateway REST API.

A stage can also inherit tags from its parent REST API. For more information, see [Tag inheritance in the Amazon API Gateway V1 API](apigateway-tagging-supported-resources.md#apigateway-tagging-inheritance).

For more information about tagging API Gateway resources, see [Tagging your API Gateway resources](apigateway-tagging.md).

**Topics**
+ [

## Set up tags for an API stage using the API Gateway console
](#set-up-tags-using-console)
+ [

## Set up tags for an API stage using the Amazon CLI
](#set-up-tags-using-cli)
+ [

## Set up tags for an API stage using the API Gateway REST API
](#set-up-tags-using-api)

## Set up tags for an API stage using the API Gateway console


The following procedure describes how to set up tags for an API stage.

**To set up tags for an API stage by using the API Gateway console**

1. Sign in to the API Gateway console.

1. Choose an existing API, or create a new API that includes resources, methods, and the corresponding integrations.

1. Choose a stage or deploy the API to a new stage.

1. In the main navigation pane, choose **Stages**.

1. Choose the **Tags** tab. You might need to choose the right arrow button to show the tab.

1. Choose **Manage tags**.

1. In the **Tag Editor**, choose **Add tag**. Enter a tag key (for example, `Department`) in the **Key** field, and enter a tag value (for example, `Sales`) in the **Value** field. Choose **Save** to save the tag.

1.  If needed, repeat step 5 to add more tags to the API stage. The maximum number of tags per stage is 50.

1.  To remove an existing tag from the stage, choose **Remove**.

1. If the API has been deployed previously in the API Gateway console, you need to redeploy it for the changes to take effect.

## Set up tags for an API stage using the Amazon CLI


You can set up tags for an API stage using the Amazon CLI using the [create-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-stage.html) command or the [tag-resource](https://docs.amazonaws.cn/cli/latest/reference/apigateway/tag-resource.html) command. You can delete one or more tags from an API stage using the [untag-resource](https://docs.amazonaws.cn/cli/latest/reference/apigateway/untag-resource.html) command. 

The following [create-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-stage.html) command adds a tag when creating a `test` stage:

```
aws apigateway create-stage --rest-api-id abc1234 --stage-name test --description 'Testing stage' --deployment-id efg456 --tag Department=Sales
```

The following [tag-resource](https://docs.amazonaws.cn/cli/latest/reference/apigateway/tag-resource.html) command adds a tag to a `prod` stage:

```
aws apigateway tag-resource --resource-arn arn:aws-cn:apigateway:us-west-2::/restapis/abc123/stages/prod --tags Department=Sales
```

The following [untag-resource](https://docs.amazonaws.cn/cli/latest/reference/apigateway/untag-resource.html) command removes the `Department=Sales` tag from the `test` stage:

```
aws apigateway untag-resource --resource-arn arn:aws-cn:apigateway:us-west-2::/restapis/abc123/stages/test --tag-keys Department 
```

## Set up tags for an API stage using the API Gateway REST API


You can set up tags for an API stage using the API Gateway REST API by doing one of the following:
+ Call [https://docs.amazonaws.cn/apigateway/latest/api/API_TagResource.html](https://docs.amazonaws.cn/apigateway/latest/api/API_TagResource.html) to tag an API stage.
+  Call [https://docs.amazonaws.cn/apigateway/latest/api/API_UntagResource.html](https://docs.amazonaws.cn/apigateway/latest/api/API_UntagResource.html) to delete one or more tags from an API stage.
+ Call [https://docs.amazonaws.cn/apigateway/latest/api/API_CreateStage.html](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateStage.html) to add one or more tags to an API stage that you're creating.

You can also call [https://docs.amazonaws.cn/apigateway/latest/api/API_GetTags.html](https://docs.amazonaws.cn/apigateway/latest/api/API_GetTags.html) to describe tags in an API stage.

### Tag an API stage


After you deploy an API (`m5zr3vnks7`) to a stage (`test`), tag the stage by calling [https://docs.amazonaws.cn/apigateway/latest/api/API_TagResource.html](https://docs.amazonaws.cn/apigateway/latest/api/API_TagResource.html). The required stage Amazon Resource Name (ARN) (`arn:aws:apigateway:us-east-1::/restapis/m5zr3vnks7/stages/test`) must be URL encoded (`arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftest`). 

```
PUT /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftest

{
  "tags" : {
    "Department" : "Sales"
  }
}
```

 You can also use the previous request to update an existing tag to a new value. 

You can add tags to a stage when calling [https://docs.amazonaws.cn/apigateway/latest/api/API_CreateStage.html](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateStage.html) to create the stage:

```
POST /restapis/<restapi_id>/stages

{
  "stageName" : "test",
  "deploymentId" : "adr134",
  "description" : "test deployment",
  "cacheClusterEnabled" : "true",
  "cacheClusterSize" : "500",
  "variables" : {
    "sv1" : "val1"
  },
  "documentationVersion" : "test",

  "tags" : {
    "Department" : "Sales",
    "Division" : "Retail"
  }
}
```

### Untag an API stage


 To remove the `Department` tag from the stage, call [https://docs.amazonaws.cn/apigateway/latest/api/API_UntagResource.html](https://docs.amazonaws.cn/apigateway/latest/api/API_UntagResource.html): 

```
DELETE /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftest?tagKeys=Department
Host: apigateway.us-east-1.amazonaws.com
Authorization: ...
```

 To remove more than one tag, use a comma-separated list of tag keys in the query expression—for example, `?tagKeys=Department,Division,…`. 

### Describe tags for an API stage


To describe existing tags on a given stage, call [https://docs.amazonaws.cn/apigateway/latest/api/API_GetTags.html](https://docs.amazonaws.cn/apigateway/latest/api/API_GetTags.html):

```
GET /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftags
Host: apigateway.us-east-1.amazonaws.com
Authorization: ...
```

The successful response is similar to the following:

```
200 OK

{
    "_links": {
        "curies": {
            "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-tags-{rel}.html",
            "name": "tags",
            "templated": true
        },
        "tags:tag": {
            "href": "/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftags"
        },
        "tags:untag": {
            "href": "/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftags{?tagKeys}",
            "templated": true
        }
    },
    "tags": {
        "Department": "Sales"
    }
}
```

# Use stage variables for a REST API in API Gateway
Use stage variables

Stage variables are key-value pairs that you can define as configuration attributes associated with a deployment stage of a REST API. They act like environment variables and can be used in your API setup and mapping templates. With deployment stages in API Gateway, you can manage multiple release stages for each API and use stage variables you can configure an API deployment stage to interact with different backend endpoints.

Stage variables are not intended to be used for sensitive data, such as credentials. To pass sensitive data to integrations, use an Amazon Lambda authorizer. You can pass sensitive data to integrations in the output of the Lambda authorizer. To learn more, see [Output from an API Gateway Lambda authorizer](api-gateway-lambda-authorizer-output.md).

## Use cases for stage variables


The following are use cases for your stage variables.

**Specify a different backend endpoint**  
Your API can pass a `GET` request as an HTTP proxy to the backend web host. You can use a stage variable so that when API callers invoke your production endpoint, API Gateway calls `example.com`. Then, when API callers invoke the beta stage, API Gateway calls a different web host, such as `beta.example.com`. Similarly, stage variables can be used to specify a different Amazon Lambda function name for each stage in your API. You can't use a stage variable to set a different integration endpoint, such as pointing the `GET` request to an HTTP proxy integration in one stage and a Lambda proxy integration in another stage.  
When specifying a Lambda function name as a stage variable value, you must configure the permissions on the Lambda function manually. When you specify a Lambda function in the API Gateway console, a Amazon CLI command will pop-up to configure the proper permissions. You can also use the following Amazon CLI command to do this.  

```
aws lambda add-permission --function-name "arn:aws-cn:lambda:us-west-2:123456789012:function:my-function" --source-arn "arn:aws-cn:execute-api:us-west-2:123456789012:api_id/*/HTTP_METHOD/resource" --principal apigateway.amazonaws.com --statement-id apigateway-access --action lambda:InvokeFunction
```

**Pass information using mapping templates**  
You can access stage variables in the mapping templates, or pass configuration parameters to your Amazon Lambda or HTTP backend. For example, you might want to reuse the same Lambda function for multiple stages in your API, but the function should read data from a different Amazon DynamoDB table depending on the stage. In the mapping templates that generate the request for the Lambda function, you can use stage variables to pass the table name to Lambda.

To use a stage variable, you first configure a stage variable, and then you assign it a value. For example, to customize the HTTP integration endpoint, first create the `url` stage variable, and then in your API's integration request, enter the stage variable value, **http://\$1\$1stageVariables.url\$1**. This value tells API Gateway to substitute your stage variable `${}` at runtime, depending on which stage your API is running. For more information, see [Set up stage variables for REST APIs in API Gateway](how-to-set-stage-variables-aws-console.md). 

# Set up stage variables for REST APIs in API Gateway


This section shows how to set up various stage variables for two deployment stages of a sample API by using the Amazon API Gateway console. To understand how to use stage variables in API Gateway, we recommend that you follow all procedures in this section.

## Prerequisites


Before you begin, make sure the following prerequisites are met: 
+ You must have an API available in API Gateway. Follow the instructions in [Develop REST APIs in API Gateway](rest-api-develop.md).
+ You must have deployed the API at least once. Follow the instructions in [Deploy REST APIs in API Gateway](how-to-deploy-api.md).
+ You must have created the first stage for a deployed API. Follow the instructions in [Create a new stage](set-up-stages.md#how-to-create-stage-console).

  

## Invoke an HTTP endpoint through an API with a stage variable


This procedure describes how to create a stage variable for an HTTP endpoint and two stages for your API. In addition, you create the stage variables, `url`, `stageName`, and `function` that are used in the following procedures in this section.

**To invoke an HTTP endpoint through an API with a stage variable**

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Create an API, and then create a `GET` method on the API's root resource. Set the integration type to **HTTP** and set the **Endpoint URL** to **http://\$1\$1stageVariables.url\$1**.

1. Deploy the API to a new stage named **beta**. 

1. In the main navigation pane, choose **Stages**, and then select the **beta** stage. 

1. On the **Stage variables** tab, choose **Edit**.

1. Choose **Add stage variable**.

1. For **Name**, enter **url**. For **value**, enter **httpbin.org/get**.

1. Choose **Add stage variable**, and then do the following:

   For **Name**, enter **stageName**. For **value**, enter **beta**.

1. Choose **Add stage variable**, and then do the following:

   For **Name**, enter **function**. For **value**, enter **HelloWorld**.

1. Choose **Save**.

1.  Now create a second stage. From the **Stages** navigation pane, choose **Create stage**. For **Stage name**, enter **prod**. Select a recent deployment from **Deployment**, and then choose **Create stage**.

1.  As with the **beta** stage, set the same three stage variables (**url**, **stageName**, and **function**) to different values (**petstore-demo-endpoint.execute-api.com/petstore/pets**, **prod**, and **HelloEveryone**), respectively. 

1. In the **Stages** navigation pane, choose **beta**. Under **Stage details**, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. This starts the **beta** stage `GET` request on the root resource of the API. 
**Note**  
The **Invoke URL** link points to the root resource of the API in its **beta** stage. Entering the URL in a web browser calls the **beta** stage `GET` method on the root resource. If methods are defined on child resources and not on the root resource itself, entering the URL in a web browser returns a `{"message":"Missing Authentication Token"}` error response. In this case, you must append the name of a specific child resource to the **Invoke URL** link. 

1. The response you get from the **beta** stage `GET` request is shown next. You can also verify the result by using a browser to navigate to **http://httpbin.org/get**. This value was assigned to the `url` variable in the **beta** stage. The two responses are identical. 

1. In the **Stages** navigation pane, choose the **prod** stage. Under **Stage details**, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. This starts the **prod** stage `GET` request on the root resource of the API. 

1. The response you get from the **prod** stage `GET` request is shown next. You can verify the result by using a browser to navigate to **http://petstore-demo-endpoint.execute-api.com/petstore/pets**. This value was assigned to the `url` variable in the **prod** stage. The two responses are identical. 

## Pass stage-specific metadata into an HTTP backend


This procedure describes how to use a stage variable value in a query parameter expression to pass stage-specific metadata into an HTTP backend. We will use the `stageName` stage variable declared in the previous procedure.

**To pass stage-specific metadata into an HTTP backend**

1. In the **Resource** navigation pane, choose the **GET** method. 

   To add a query string parameter to the method's URL, choose the **Method request** tab, and then in the **Method request settings** section, choose **Edit**. 

1. Choose **URL query string parameters** and do the following:

   1. Choose **Add query string**.

   1. For **Name**, enter **stageName**.

   1. Keep **Required** and **Caching** turned off.

1. Choose **Save**.

1. Choose the **Integration request** tab, and then in the **Integration request settings** section, choose **Edit**.

1. For **Endpoint URL**, append **?stageName=\$1\$1stageVariables.stageName\$1** to the previously defined URL value, so the entire **Endpoint URL** is **http://\$1\$1stageVariables.url\$1?stageName=\$1\$1stageVariables.stageName\$1**.

1. Choose **Deploy API** and select the **beta** stage.

1. In the main navigation pane, choose **Stages**. In the **Stages** navigation pane, choose **beta**. Under **Stage details**, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. 
**Note**  
 We use the beta stage here because the HTTP endpoint (as specified by the `url` variable "http://httpbin.org/get") accepts query parameter expressions and returns them as the `args` object in its response. 

1. You get the following response. Notice that `beta`, assigned to the `stageName` stage variable, is passed in the backend as the `stageName` argument. 

    

## Invoke a Lambda function through an API with a stage variable


This procedure describes how to use a stage variable to call a Lambda function as a backend of your API. You use the `function` stage variable declared in [Invoke an HTTP endpoint through an API with a stage variable](#how-to-set-stage-variables-aws-console-http-endpoint).

 When setting a Lambda function as the value of a stage variable, use the function's local name, possibly including its alias or version specification, as in **HelloWorld**, **HelloWorld:1** or **HelloWorld:alpha**. Do not use the function's ARN (for example, **arn:aws:lambda:us-east-1:123456789012:function:HelloWorld**). The API Gateway console assumes the stage variable value for a Lambda function as the unqualified function name and expands the given stage variable into an ARN. 

**To invoke a Lambda function through an API with a stage variable**

1. Create a Lambda function named **HelloWorld** using the default Node.js runtime. The code must contain the following:

   ```
   export const handler = function(event, context, callback) {
       if (event.stageName)
           callback(null, 'Hello, World! I\'m calling from the ' + event.stageName + ' stage.');
       else
           callback(null, 'Hello, World! I\'m not sure where I\'m calling from...');
   };
   ```

   For more information on how to create a Lambda function, see [Getting started with the REST API console](getting-started-rest-new-console.md#getting-started-rest-new-console-create-function).

1. In the **Resources** pane, select **Create resource**, and then do the following:

   1. For **Resource path**, select **/**.

   1. For **Resource name**, enter **lambdav1**.

   1. Choose **Create resource**.

1. Choose the **/lambdav1** resource, and then choose **Create method**.

   Then, do the following:

   1. For **Method type**, select **GET**.

   1. For **Integration type**, select **Lambda function**.

   1. Keep **Lambda proxy integration** turned off.

   1. For **Lambda function**, enter `${stageVariables.function}`.
**Tip**  
When prompted with the **Add permission command**, copy the [add-permission](https://docs.amazonaws.cn/cli/latest/reference/lambda/add-permission.html) command. Run the command on each Lambda function that will be assigned to the `function` stage variable. For example, if the `$stageVariables.function` value is `HelloWorld`, run the following Amazon CLI command:   

      ```
      aws lambda add-permission --function-name arn:aws:lambda:us-east-1:account-id:function:HelloWorld --source-arn arn:aws:execute-api:us-east-1:account-id:api-id/*/GET/lambdav1 --principal apigateway.amazonaws.com --statement-id statement-id-guid --action lambda:InvokeFunction
      ```
 Failing to do so results in a `500 Internal Server Error` response when invoking the method. Replace `${stageVariables.function}` with the Lambda function name that is assigned to the stage variable.   
 

   1. Choose **Create method**.

1. Deploy the API to both the **prod** and **beta** stages.

1. In the main navigation pane, choose **Stages**. In the **Stages** navigation pane, choose **beta**. Under **Stage details**, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. Append **/lambdav1** to the URL before you press enter.

   You get the following response.

   ```
   "Hello, World! I'm not sure where I'm calling from..."
   ```

## Pass stage-specific metadata to a Lambda function through a stage variable


This procedure describes how to use a stage variable to pass stage-specific configuration metadata into a Lambda function. You create a `POST` method and an input mapping template to generate payload using the `stageName` stage variable you declared earlier.

**To pass stage-specific metadata to a Lambda function through a stage variable**

1. Choose the **/lambdav1** resource, and then choose **Create method**.

   Then, do the following:

   1. For **Method type**, select **POST**.

   1. For **Integration type**, select **Lambda function**.

   1. Keep **Lambda proxy integration** turned off.

   1. For **Lambda function**, enter `${stageVariables.function}`.

   1. When prompted with the **Add permission command**, copy the the [add-permission](https://docs.amazonaws.cn/cli/latest/reference/lambda/add-permission.html) command. Run the command on each Lambda function that will be assigned to the `function` stage variable.

   1. Choose **Create method**.

1. Choose the **Integration request** tab, and then in the **Integration request settings** section, choose **Edit**.

1. Choose **Mapping templates**, and then choose **Add mapping template**.

1. For **Content type**, enter **application/json**.

1. For **Template body**, enter the following template:

   ```
   #set($inputRoot = $input.path('$'))
   {
       "stageName" : "$stageVariables.stageName"
   }
   ```
**Note**  
 In a mapping template, a stage variable must be referenced within quotes (as in `"$stageVariables.stageName"` or `"${stageVariables.stageName}"`). In other places, it must be referenced without quotes (as in `${stageVariables.function}`). 

1. Choose **Save**.

1. Deploy the API to both the **beta** and **prod** stages.

1. To use a REST API client to pass stage-specific metadata, do the following:

   1. In the **Stages** navigation pane, choose **beta**. Under **Stage details**, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in the input field of a REST API client. Append **/lambdav1** before you submit your request.

      You get the following response.

      ```
      "Hello, World! I'm calling from the beta stage."
      ```

   1. In the **Stages** navigation pane, choose **prod**. Under **Stage details**, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in the input field of a REST API client. Append **/lambdav1** before you submit your request.

      You get the following response.

      ```
      "Hello, World! I'm calling from the prod stage."
      ```

1. To use the **Test** feature to pass stage-specific metadata, do the following:

   1. In the **Resources** navigation pane, choose the **Test** tab. You might need to choose the right arrow button to show the tab.

   1. For **function**, enter **HelloWorld**.

   1. For **stageName**, enter **beta**.

   1. Choose **Test**. You do not need to add a body to your `POST` request.

      You get the following response.

      ```
      "Hello, World! I'm calling from the beta stage."
      ```

   1. You can repeat the previous steps to test the **Prod** stage. For **stageName**, enter **Prod**.

      You get the following response.

      ```
      "Hello, World! I'm calling from the prod stage."
      ```

# API Gateway stage variables reference for REST APIs in API Gateway
Stage variables reference

 You can use API Gateway stage variables in the following cases.

## Parameter mapping expressions


A stage variable can be used in a parameter mapping expression for an API method's request or response header parameter, without any partial substitution. In the following example, the stage variable is referenced without the `$` and the enclosing `{...}`. 
+ `stageVariables.<variable_name>`

## Mapping templates


 A stage variable can be used anywhere in a mapping template, as shown in the following examples. 
+  `{ "name" : "$stageVariables.<variable_name>"}`
+ `{ "name" : "${stageVariables.<variable_name>}"}`

## HTTP integration URIs


A stage variable can be used as part of an HTTP integration URL, as shown in the following examples:
+ A full URI without protocol – `http://${stageVariables.<variable_name>}`
+ A full domain – `http://${stageVariables.<variable_name>}/resource/operation`
+ A subdomain – `http://${stageVariables.<variable_name>}.example.com/resource/operation`
+ A path – `http://example.com/${stageVariables.<variable_name>}/bar`
+ A query string – `http://example.com/foo?q=${stageVariables.<variable_name>}` 

## Amazon integration URIs


 A stage variable can be used as part of Amazon URI action or path components, as shown in the following example.
+ `arn:aws:apigateway:<region>:<service>:${stageVariables.<variable_name>}`

## Amazon integration URIs (Lambda functions)


 A stage variable can be used in place of a Lambda function name, or version/alias, as shown in the following examples. 
+ `arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/arn:aws:lambda:<region>:<account_id>:function:${stageVariables.<function_variable_name>}/invocations`
+ `arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/arn:aws:lambda:<region>:<account_id>:function:<function_name>:${stageVariables.<version_variable_name>}/invocations`

**Note**  
To use a stage variable for a Lambda function, the function must be in the same account as the API. Stage variables don't support cross-account Lambda functions.

## Amazon Cognito user pool


A stage variable can be used in place of a Amazon Cognito user pool for a `COGNITO_USER_POOLS` authorizer.
+ `arn:aws:cognito-idp:<region>:<account_id>:userpool/${stageVariables.<variable_name>}`

## Amazon integration credentials


 A stage variable can be used as part of Amazon user/role credential ARN, as shown in the following example. 
+  `arn:aws:iam::<account_id>:${stageVariables.<variable_name>}` 

# Set up an API Gateway canary release deployment
Set up a canary release deployment

[Canary release](https://martinfowler.com/bliki/CanaryRelease.html) is a software development strategy in which a new version of an API (as well as other software) is deployed for testing purposes, and the base version remains deployed as a production release for normal operations on the same stage. For purposes of discussion, we refer to the base version as a production release in this documentation. Although this is reasonable, you are free to apply canary release on any non-production version for testing.

In a canary release deployment, total API traffic is separated at random into a production release and a canary release with a pre-configured ratio. Typically, the canary release receives a small percentage of API traffic and the production release takes up the rest. The updated API features are only visible to API traffic through the canary. You can adjust the canary traffic percentage to optimize test coverage or performance. 

By keeping canary traffic small and the selection random, most users are not adversely affected at any time by potential bugs in the new version, and no single user is adversely affected all the time.

After the test metrics pass your requirements, you can promote the canary release to the production release and disable the canary from the deployment. This makes the new features available in the production stage. 

**Topics**
+ [

## Canary release deployment in API Gateway
](#api-gateway-canary-release-deployment-overview)
+ [

# Create a canary release deployment
](create-canary-deployment.md)
+ [

# Update a canary release
](update-canary-deployment.md)
+ [

# Promote a canary release
](promote-canary-deployment.md)
+ [

# Turn off a canary release
](delete-canary-deployment.md)

## Canary release deployment in API Gateway


 In API Gateway, a canary release deployment uses the deployment stage for the production release of the base version of an API, and attaches to the stage a canary release for the new versions, relative to the base version, of the API. The stage is associated with the initial deployment and the canary with subsequent deployments. At the beginning, both the stage and the canary point to the same API version. We use stage and production release interchangeably and use canary and canary release interchangeably throughout this section.

To deploy an API with a canary release, you create a canary release deployment by adding [canary settings](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings) to the [stage](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html) of a regular [deployment](https://docs.amazonaws.cn/apigateway/latest/api/API_Deployment.html). The canary settings describe the underlying canary release and the stage represents the production release of the API within this deployment. To add canary settings, set `canarySettings` on the deployment stage and specify the following: 
+  A deployment ID, initially identical to the ID of the base version deployment set on the stage. 
+  A [percentage of API traffic](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#percentTraffic), between 0.0 and 100.0 inclusive, for the canary release. 
+  [Stage variables for the canary release](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#stageVariableOverrides) that can override production release stage variables. 
+  The [use of the stage cache](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#useStageCache) for canary requests, if the [useStageCache](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#useStageCache) is set and API caching is enabled on the stage.

 After a canary release is enabled, the deployment stage cannot be associated with another non-canary release deployment until the canary release is disabled and the canary settings removed from the stage. 

When you enable API execution logging, the canary release has its own logs and metrics generated for all canary requests. They are reported to a production stage CloudWatch Logs log group as well as a canary-specific CloudWatch Logs log group. The same applies to access logging. The separate canary-specific logs are helpful to validate new API changes and decide whether to accept the changes and promote the canary release to the production stage, or to discard the changes and revert the canary release from the production stage.

The production stage execution log group is named `API-Gateway-Execution-Logs/{rest-api-id}/{stage-name}` and the canary release execution log group is named `API-Gateway-Execution-Logs/{rest-api-id}/{stage-name}/Canary`. For access logging, you must create a new log group or choose an existing one. The canary release access log group name has the `/Canary` suffix appended to the selected log group name. 

A canary release can use the stage cache, if enabled, to store responses and use cached entries to return results to the next canary requests, within a pre-configured time-to-live (TTL) period. 

In a canary release deployment, the production release and canary release of the API can be associated with the same version or with different versions. When they are associated with different versions, responses for production and canary requests are cached separately and the stage cache returns corresponding results for production and canary requests. When the production release and canary release are associated with the same deployment, the stage cache uses a single cache key for both types of requests and returns the same response for the same requests from the production release and canary release. 

# Create a canary release deployment


You create a canary release deployment when deploying the API with [canary settings](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateDeployment.html#canarySettings) as an additional input to the [deployment creation](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateDeployment.html) operation. 

You can also create a canary release deployment from an existing non-canary deployment by making a [https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateStage.html](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateStage.html) request to add the canary settings on the stage.

When creating a non-canary release deployment, you can specify a non-existing stage name. API Gateway creates one if the specified stage does not exist. However, you cannot specify any non-existing stage name when creating a canary release deployment. You will get an error and API Gateway will not create any canary release deployment. 

 You can create a canary release deployment in API Gateway using the API Gateway console, the Amazon CLI, or an Amazon SDK.

**Topics**
+ [

## Create a canary deployment using the API Gateway console
](#create-canary-deployment-using-console)
+ [

## Create a canary deployment using the Amazon CLI
](#create-canary-deployment-using-cli)

## Create a canary deployment using the API Gateway console


To use the API Gateway console to create a canary release deployment, follow the instructions below:<a name="to-create-canary-release-on-new-deployment"></a>

**To create the initial canary release deployment**

1.  Sign in to the API Gateway console.

1.  Choose an existing REST API or create a new REST API.

1.  In the main navigation pane, choose **Resources**, and then choose **Deploy API**. Follow the on-screen instructions in **Deploy API** to deploy the API to a new stage. 

   So far, you have deployed the API to a production release stage. Next, you configure canary settings on the stage and, if needed, also enable caching, set stage variables, or configure API execution or access logs.

1.  To enable API caching or associate an Amazon WAF web ACL with the stage, in the **Stage details** section, choose **Edit**. For more information, see [Cache settings for REST APIs in API Gateway](api-gateway-caching.md) or [To associate an Amazon WAF web ACL with an API Gateway API stage using the API Gateway console](apigateway-control-access-aws-waf.md#apigateway-control-access-aws-waf-console).

1.  To configure execution or access logging, in the **Logs and tracing** section, choose **Edit** and follow the on-screen instructions. For more information, see [Set up CloudWatch logging for REST APIs in API Gateway](set-up-logging.md).

1. To set stage variables, choose the **Stage variables** tab and follow the on-screen instructions to add or modify stage variables. For more information, see [Use stage variables for a REST API in API Gateway](stage-variables.md).

1.  Choose the **Canary** tab, and then choose **Create canary**. You might need to choose the right arrow button to show the **Canary** tab.

1.  Under **Canary settings**, for **Canary**, enter the percentage of requests to be diverted to the canary.

1. If desired, select **Stage cache** to turn on caching for the canary release. The cache is not available for the canary release until API caching is enabled.

1. To override existing stage variables, for **Canary override**, enter a new stage variable value.

After the canary release is initialized on the deployment stage, you change the API and want to test the changes. You can redeploy the API to the same stage so that both the updated version and the base version are accessible through the same stage. The following steps describe how to do that. <a name="to-deploy-latest-api-to-canary-release"></a>

**To deploy the latest API version to a canary**

1.  With each update of the API, choose **Deploy API**.

1.  In **Deploy API**, choose the stage that contains a canary from the **Deployment stage** dropdown list. 

1.  (Optional) Enter a description for **Deployment description**. 

1.  Choose **Deploy** to push the latest API version to the canary release.

1.  If desired, reconfigure the stage settings, logs, or canary settings, as describe in [To create the initial canary release deployment](#to-create-canary-release-on-new-deployment).

 As a result, the canary release points to the latest version while the production release still points to the initial version of the API. The [https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings) now has a new **deploymentId** value, whereas the stage still has the initial [https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#deploymentId](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#deploymentId) value. Behind the scenes, the console calls [https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateStage.html](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateStage.html).

## Create a canary deployment using the Amazon CLI


**To create a canary deployment for a new stage**

1. Use the following [create-deployment](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-deployment.html) command to create a deployment with two stage variables, but without a canary:

   ```
   aws apigateway create-deployment \
       --variables sv0=val0,sv1=val1 \
       --rest-api-id abcd1234 \
       --stage-name 'prod'
   ```

   The output will look like the following:

   ```
   {
       "id": "du4ot1", 
       "createdDate": 1511379050
   }
   ```

1. Use the following [create-deployment](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-deployment.html) command to create a canary deployment on the `prod` stage:

   ```
   aws apigateway create-deployment \
       --rest-api-id abcd1234 \
       --canary-settings percentTraffic=10.5,stageVariableOverrides={sv1='val2',sv2='val3'},useStageCache=false \
       --stage-name 'prod'
   ```

   The output will look like the following:

   ```
   {
       "id": "a6rox0", 
       "createdDate": 1511379433
   }
   ```

   The resulting deployment `id` identifies the test version of the API for the canary release. As a result, the associated stage is canary-enabled.

1. (Optional) Use the following [get-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/get-stage.html) command to view the stage representation:

   ```
   aws apigateway get-stage --rest-api-id acbd1234 --stage-name prod
   ```

   The following shows a representation of the `Stage` as the output of the command:

   ```
   {
       "stageName": "prod", 
       "variables": {
           "sv0": "val0", 
           "sv1": "val1"
       }, 
       "cacheClusterEnabled": false, 
       "cacheClusterStatus": "NOT_AVAILABLE", 
       "deploymentId": "du4ot1", 
       "lastUpdatedDate": 1511379433, 
       "createdDate": 1511379050, 
       "canarySettings": {
           "percentTraffic": 10.5, 
           "deploymentId": "a6rox0", 
           "useStageCache": false, 
           "stageVariableOverrides": {
               "sv2": "val3", 
               "sv1": "val2"
           }
       }, 
       "methodSettings": {}
   }
   ```

   In this example, the base version of the API will use the stage variables of `{"sv0":val0", "sv1":val1"}`, while the test version uses the stage variables of `{"sv1":val2", "sv2":val3"}`. Both the production release and canary release use the same stage variable of `sv1`, but with different values, `val1` and `val2`, respectively. The stage variable of `sv0` is used solely in the production release and the stage variable of `sv2` is used in the canary release only. 

You can also create a canary release deployment from an existing regular deployment by updating the stage to enable a canary.

**To create a canary release deployment from an existing deployment**

1. Use the [create-deployment](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-deployment.html) command to create a deployment without a canary:

   ```
   aws apigateway create-deployment \
       --variables sv0=val0,sv1=val1 \  
       --rest-api-id abcd1234 \
       --stage-name 'beta'
   ```

1. Use the [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command to update the stage to enable a canary:

   ```
   aws apigateway update-stage \
       --rest-api-id abcd1234 \
       --stage-name 'beta' \
       --patch-operations '[{
               "op": "replace",
               "value": "0.0",
               "path": "/canarySettings/percentTraffic"
           }, {
               "op": "copy",
               "from": "/canarySettings/stageVariableOverrides",
               "path": "/variables"
           }, {
               "op": "copy",
               "from": "/canarySettings/deploymentId",
               "path": "/deploymentId"
           }]'
   ```

   The output will look like the following:

   ```
   {
       "stageName": "beta", 
       "variables": {
           "sv0": "val0", 
           "sv1": "val1"
       }, 
       "cacheClusterEnabled": false, 
       "cacheClusterStatus": "NOT_AVAILABLE", 
       "deploymentId": "cifeiw", 
       "lastUpdatedDate": 1511381930, 
       "createdDate": 1511380879, 
       "canarySettings": {
           "percentTraffic": 10.5, 
           "deploymentId": "cifeiw", 
           "useStageCache": false, 
           "stageVariableOverrides": {
               "sv2": "val3", 
               "sv1": "val2"
           }
       }, 
       "methodSettings": {}
   }
   ```

   Because you enabled a canary on an existing version of the API, both the production release (`Stage`) and canary release (`canarySettings`) point to the same deployment. After you change the API and deploy it to this stage again, the new version will be in the canary release, while the base version remains in the production release. This is manifested in the stage evolution when the `deploymentId` in the canary release is updated to the new deployment `id` and the `deploymentId` in the production release remains unchanged.

# Update a canary release


 After a canary release is deployed, you may want to adjust the percentage of the canary traffic or enable or disable the use of a stage cache to optimize the test performance. You can also modify stage variables used in the canary release when the execution context is updated. To make such updates, call the [https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateStage.html](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateStage.html) operation with new values on [canarySettings](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings). 

You can update a canary release using the API Gateway console, the Amazon CLI [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command or an Amazon SDK.

**Topics**
+ [

## Update a canary release using the API Gateway console
](#update-canary-deployment-using-console)
+ [

## Update a canary release using the Amazon CLI
](#update-canary-deployment-using-cli)

## Update a canary release using the API Gateway console


To use the API Gateway console to update existing canary settings on a stage, do the following:

**To update existing canary settings**

1.  Sign in to the API Gateway console and choose an existing REST API.

1.  In the main navigation pane, choose **Stages**, and then choose an existing stage.

1.  Choose the **Canary** tab, and then choose **Edit**. You might need to choose the right arrow button to show the **Canary** tab. 

1.  Update the **Request distribution** by increasing or decreasing the percentage number between 0.0 and 100.0, inclusive. 

1.  Select or clear the **Stage cache** the check box. 

1.  Add, remove, or modify **Canary stage variables**.

1.  Choose **Save**.

## Update a canary release using the Amazon CLI


To use the Amazon CLI to update a canary, use the [https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command and modify the patch operation for each parameter of the canary.

The following [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command updates if the canary uses the stage cache:

```
aws apigateway update-stage \
    --rest-api-id {rest-api-id} \
    --stage-name '{stage-name}' \
    --patch-operations op=replace,path=/canarySettings/useStageCache,value=true
```

The following [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command updates the canary traffic percentage:

```
aws apigateway update-stage \
    --rest-api-id {rest-api-id} \
    --stage-name '{stage-name}' \
    --patch-operations op=replace,path=/canarySettings/percentTraffic,value=25.0
```

The following [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) updates stage variables. The example shows how to create a new stage variable named `newVar`, override the `var2` stage variable, and remove the `var1` stage variable:

```
aws apigateway update-stage  \
    --rest-api-id {rest-api-id} \
    --stage-name '{stage-name}'  \
    --patch-operations '[{                                      
        "op": "replace",                                        
        "path": "/canarySettings/stageVariableOverrides/newVar", 
        "value": "newVal"                                      
      }, { 
        "op": "replace",                                        
        "path": "/canarySettings/stageVariableOverrides/var2",   
        "value": "val4"                                        
      }, {                                                      
        "op": "remove",                                         
        "path": "/canarySettings/stageVariableOverrides/var1"    
      }]'
```

You can update all of the above by combining the operations into a single `patch-operations` value:

```
aws apigateway update-stage  \
    --rest-api-id {rest-api-id} \
    --stage-name '{stage-name}' \
    --patch-operations '[{                                       
        "op": "replace",                                         
        "path": "/canarySettings/percentTraffic",                        
        "value": "20.0"                                          
    }, {                                                         
        "op": "replace",                                         
        "path": "/canarySettings/useStageCache",                        
        "value": "true"                                          
    }, {                                                         
        "op": "remove",                                          
        "path": "/canarySettings/stageVariableOverrides/var1"    
    }, {                                                         
        "op": "replace",                                         
        "path": "/canarySettings/stageVariableOverrides/newVar", 
        "value": "newVal"                                        
    }, {                                                         
        "op": "replace",                                         
        "path": "/canarySettings/stageVariableOverrides/val2",   
        "value": "val4"                                          
      }]'
```



# Promote a canary release


When you promote a canary release, the canary release replaces the current stage settings. Promoting a canary release does not disable the canary on the stage. To disable a canary, you must remove the canary settings on the stage. To promote a canary, do the following.
+ Reset the [deployment ID](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#deploymentId) of the stage with the [deployment ID](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings) settings of the canary. This updates the API snapshot of the stage with the snapshot of the canary, making the test version the production release as well.
+ Update stage variables with canary stage variables, if any. This updates the API execution context of the stage with that of the canary. Without this update, the new API version may produce unexpected results if the test version uses different stage variables or different values of existing stage variables.
+ Set the percentage of canary traffic to 0.0%.

**Topics**
+ [

## Promote a canary release using the API Gateway console
](#promote-canary-release-deployment-console)
+ [

## Promote a canary release using the Amazon CLI
](#promote-canary-release-cli)

## Promote a canary release using the API Gateway console


To use the API Gateway console to promote a canary release deployment, do the following:

**To promote a canary release deployment**

1.  Sign in to the API Gateway console and choose an existing API in the primary navigation pane.

1.  In the main navigation pane, choose **Stages**, and then choose an existing stage.

1.  Choose the **Canary** tab.

1.  Choose **Promote canary**.

1.  Confirm changes to be made and choose **Promote canary**.

After the promotion, the production release references the same API version (**deploymentId**) as the canary release. You can verify this using the Amazon CLI. For example, see [Promote a canary release using the Amazon CLI](#promote-canary-release-cli). 

## Promote a canary release using the Amazon CLI


To promote a canary release to the production release using the Amazon CLI commands, call the `update-stage` command to copy the canary-associated `deploymentId` to the stage-associated `deploymentId`, to reset the canary traffic percentage to zero (`0.0`), and, to copy any canary-bound stage variables to the corresponding stage-bound ones. 

Suppose we have a canary release deployment, described by a stage similar to the following: 

```
{
    "_links": {
        ...
    },
    "accessLogSettings": {
        ...
    },
    "cacheClusterEnabled": false,
    "cacheClusterStatus": "NOT_AVAILABLE",
    "canarySettings": {
        "deploymentId": "eh1sby",
        "useStageCache": false,
        "stageVariableOverrides": {
            "sv2": "val3",
            "sv1": "val2"
        },
        "percentTraffic": 10.5
    },
    "createdDate": "2017-11-20T04:42:19Z",
    "deploymentId": "nfcn0x",
    "lastUpdatedDate": "2017-11-22T00:54:28Z",
    "methodSettings": {
        ...
    },
    "stageName": "prod",
    "variables": {
        "sv1": "val1"
    }
}
```

Use the following [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command to promote the canary:

```
aws apigateway update-stage  \
    --rest-api-id {rest-api-id}  \
    --stage-name '{stage-name}'  \
    --patch-operations '[{                                
        "op": "replace",                                  
        "value": "0.0",                                    
        "path": "/canarySettings/percentTraffic"         
      }, {                                                
        "op": "copy",                                     
        "from": "/canarySettings/stageVariableOverrides", 
        "path": "/variables"                             
      }, {                                                
        "op": "copy",                                     
        "from": "/canarySettings/deploymentId",           
        "path": "/deploymentId"                           
      }]'
```

The output will look like the following:

```
{
    "_links": {
        ...
    },
    "accessLogSettings": {
        ...
    },
    "cacheClusterEnabled": false,
    "cacheClusterStatus": "NOT_AVAILABLE",
    "canarySettings": {
        "deploymentId": "eh1sby",
        "useStageCache": false,
        "stageVariableOverrides": {
            "sv2": "val3",
            "sv1": "val2"
        },
        "percentTraffic": 0
    },
    "createdDate": "2017-11-20T04:42:19Z",
    "deploymentId": "eh1sby",
    "lastUpdatedDate": "2017-11-22T05:29:47Z",
    "methodSettings": {
        ...
    },
    "stageName": "prod",
    "variables": {
        "sv2": "val3",
        "sv1": "val2"
    }
}
```

Promoting a canary release to the stage does not disable the canary and the deployment remains to be a canary release deployment. To make it a regular production release deployment, you must disable the canary settings. For more information about how to disable a canary release deployment, see [Turn off a canary release](delete-canary-deployment.md).

# Turn off a canary release


To turn off a canary release deployment is to set the [https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings) to null to remove it from the stage. 

You can disable a canary release deployment using the API Gateway console, the Amazon CLI, or an Amazon SDK.

**Topics**
+ [

## Turn off a canary release using the API Gateway console
](#delete-canary-release-console)
+ [

## Turn off a canary release using the Amazon CLI
](#delete-canary-release-cli)

## Turn off a canary release using the API Gateway console


To use the API Gateway console to turn off a canary release deployment, use the following steps:

**To turn off a canary release deployment**

1. Sign in to the API Gateway console and choose an existing API in the main navigation pane.

1. In the main navigation pane, choose **Stages**, and then choose an existing stage.

1.  Choose the **Canary** tab.

1.  Choose **Delete**.

1.  Confirm you want to delete the canary by choosing **Delete**.

As a result, the [https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings) property becomes `null` and is removed from the deployment [stage](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html). You can verify this using the Amazon CLI. For example, see [Turn off a canary release using the Amazon CLI](#delete-canary-release-cli).

## Turn off a canary release using the Amazon CLI


The following [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command turns off the canary release deployment:

```
aws apigateway update-stage \
    --rest-api-id abcd1234 \
    --stage-name canary \
    --patch-operations '[{"op":"remove", "path":"/canarySettings"}]'
```

The output looks like the following:

```
{
    "stageName": "prod", 
    "accessLogSettings": {
        ...
    }, 
    "cacheClusterEnabled": false, 
    "cacheClusterStatus": "NOT_AVAILABLE", 
    "deploymentId": "nfcn0x", 
    "lastUpdatedDate": 1511309280, 
    "createdDate": 1511152939, 
    "methodSettings": {
        ...
    }
}
```

 As shown in the output, the [canarySettings](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html#canarySettings) property is no longer present in the [stage](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html) of a canary-disabled deployment.

# Updates to REST APIs that require redeployment
Redeploy a REST API

Maintaining an API amounts to viewing, updating and deleting the existing API setups. You can maintain an API using the API Gateway console, Amazon CLI, Amazon CloudFormation, an SDK or the API Gateway REST API. Updating an API involves modifying certain resource properties or configuration settings of the API. Resource updates require redeploying the API, where configuration updates do not. 

The following table describes API resources that require redeployment of your API when you update them. 


| Resource | Notes | 
| --- | --- | 
| [ApiKey](https://docs.amazonaws.cn/apigateway/latest/api/API_ApiKey.html) | For applicable properties and supported operations, see [apikey:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateApiKey.html). The update requires redeploying the API. | 
| [Authorizer](https://docs.amazonaws.cn/apigateway/latest/api/API_Authorizer.html) | For applicable properties and supported operations, see [authorizer:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateAuthorizer.html). The update requires redeploying the API. | 
|  [disableExecuteApiEndpoint](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateRestApi.html#apigw-UpdateRestApi-response-disableExecuteApiEndpoint) | The update requires modifying any stage on the API such as redeploying the API to a stage. | 
| [DocumentationPart](https://docs.amazonaws.cn/apigateway/latest/api/API_DocumentationPart.html) | For applicable properties and supported operations, see [documentationpart:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateDocumentationPart.html). The update requires redeploying the API. | 
| [DocumentationVersion](https://docs.amazonaws.cn/apigateway/latest/api/API_DocumentationVersion.html) | For applicable properties and supported operations, see [documentationversion:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateDocumentationVersion.html). The update requires redeploying the API. | 
| [GatewayResponse](https://docs.amazonaws.cn/apigateway/latest/api/API_GatewayResponse.html) | For applicable properties and supported operations, see [gatewayresponse:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateGatewayResponse.html#remarks). The update requires redeploying the API. | 
| [Integration](https://docs.amazonaws.cn/apigateway/latest/api/API_Integration.html) |  For applicable properties and supported operations, see [integration:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateIntegration.html). The update requires redeploying the API.  | 
| [IntegrationResponse](https://docs.amazonaws.cn/apigateway/latest/api/API_IntegrationResponse.html) | For applicable properties and supported operations, see [integrationresponse:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateIntegrationResponse.html). The update requires redeploying the API. | 
| [Method](https://docs.amazonaws.cn/apigateway/latest/api/API_Method.html) | For applicable properties and supported operations, see [method:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateMethod.html). The update requires redeploying the API. | 
| [MethodResponse](https://docs.amazonaws.cn/apigateway/latest/api/API_MethodResponse.html) | For applicable properties and supported operations, see [methodresponse:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateMethodResponse.html). The update requires redeploying the API. | 
| [Model](https://docs.amazonaws.cn/apigateway/latest/api/API_Model.html) | For applicable properties and supported operations, see [model:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateModel.html). The update requires redeploying the API. | 
| [RequestValidator](https://docs.amazonaws.cn/apigateway/latest/api/API_RequestValidator.html) | For applicable properties and supported operations, see [requestvalidator:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateRequestValidator.html). The update requires redeploying the API. | 
| [Resource](https://docs.amazonaws.cn/apigateway/latest/api/API_Resource.html) | For applicable properties and supported operations, see [resource:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateResource.html). The update requires redeploying the API. | 
| [RestApi](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateRestApi.html) | For applicable properties and supported operations, see [restapi:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateRestApi.html). The update requires redeploying the API. This includes modifying resource policies. | 
| [VpcLink](https://docs.amazonaws.cn/apigateway/latest/api/API_VpcLink.html) | For applicable properties and supported operations, see [vpclink:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateVpcLink.html). The update requires redeploying the API. | 

The following table describes API configurations that don't require redeployment of your API when you update them.


| Configuration | Notes | 
| --- | --- | 
| [Account](https://docs.amazonaws.cn/apigateway/latest/api/API_GetAccount.html) |  For applicable properties and supported operations, see [account:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateAccount.html). The update does not require redeploying the API.  | 
| [Deployment](https://docs.amazonaws.cn/apigateway/latest/api/API_Deployment.html) | For applicable properties and supported operations, see [deployment:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateDeployment.html).  | 
| [DomainName](https://docs.amazonaws.cn/apigateway/latest/api/API_DomainName.html) | For applicable properties and supported operations, see [domainname:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateDomainName.html). The update does not require redeploying the API. | 
| [BasePathMapping](https://docs.amazonaws.cn/apigateway/latest/api/API_BasePathMapping.html) |  For applicable properties and supported operations, see [basepathmapping:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateBasePathMapping.html). The update does not require redeploying the API.  | 
| [IP address type](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateRestApi.html) |  The update does not require redeploying the API.  | 
| [Stage](https://docs.amazonaws.cn/apigateway/latest/api/API_Stage.html) |  For applicable properties and supported operations, see [stage:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateStage.html). The update does not require redeploying the API.  | 
| [Usage](https://docs.amazonaws.cn/apigateway/latest/api/API_GetUsage.html) |  For applicable properties and supported operations, see [usage:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateUsage.html). The update does not require redeploying the API.  | 
| [UsagePlan](https://docs.amazonaws.cn/apigateway/latest/api/API_UsagePlan.html) | For applicable properties and supported operations, see [usageplan:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateUsagePlan.html). The update does not require redeploying the API. | 

# Custom domain name for public REST APIs in API Gateway
Custom domain names

*Custom domain names* are simpler and more intuitive URLs that you can provide to your API users.

After deploying your API, you (and your customers) can invoke the API using the default base URL of the following format: 

```
https://api-id.execute-api.region.amazonaws.com/stage
```

where *api-id* is generated by API Gateway, *region* is the Amazon Region, and *stage* is specified by you when deploying the API.

The hostname portion of the URL, `api-id.execute-api.region.amazonaws.com` refers to an API endpoint. The default API endpoint name is randomly generated, difficult to recall, and not user-friendly.

With custom domain names, you can set up your API's hostname, and choose a base path (for example, `myservice`) to map the alternative URL to your API. For example, a more user-friendly API base URL can become:

```
https://api.example.com/myservice
```

**Note**  
For information about custom domain names for private APIs, see [Custom domain names for private APIs in API Gateway](apigateway-private-custom-domains.md).

## Considerations


The following considerations might impact your use of a custom domain name:
+ You can disable the default endpoint for your API. Clients can still connect to your default endpoint, but they will receive a `403 Forbidden` status code.
+ A Regional custom domain name can be associated with REST APIs and HTTP APIs. You can use the [API Gateway Version 2 APIs](https://docs.amazonaws.cn/apigatewayv2/latest/api-reference/api-reference.html) to create and manage Regional custom domain names for REST APIs. 
+ A custom domain name must be unique within a Region across all Amazon accounts. 
+ You can migrate your custom domain name between edge-optimized and Regional endpoints, but you can't migrate a public custom domain to a private custom domain name.
+ You must create or update your DNS provider's resource record to map to your API endpoint. Without such a mapping, API requests bound for the custom domain name cannot reach API Gateway.
+ You can support an almost infinite number of domain names without exceeding the default quota by using a wildcard certificate. For more information, see [Wildcard custom domain names](#wildcard-custom-domain-names).
+ You can choose a security policy for your custom domain name. For more information, see [Choose a security policy for your custom domain in API Gateway](apigateway-custom-domain-tls-version.md).
+ To configure API mappings with multiple levels, you must use a Regional custom domain name and use the TLS 1.2 security policy.

## Prerequisites for custom domain names


The following are prerequisites for creating a public or private custom domain name. For information about custom domain names for private APIs, see [Custom domain names for private APIs in API Gateway](apigateway-private-custom-domains.md).

### Register a domain name


You must have a registered internet domain name in order to set up custom domain names for your APIs. You can register your internet domain name using [Amazon Route 53](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/) or using a third-party domain registrar of your choice. Your custom domain name can be the name of a subdomain or the root domain (also known as the "zone apex") of a registered internet domain.

Your domain name must follow the [RFC 1035](https://tools.ietf.org/html/rfc1035#section-2.3.4) specification and can have a maximum of 63 octets per label and 255 octets in total.

### Specify the certificate for your custom domain name


Before setting up a custom domain name for an API, you must have an SSL/TLS certificate ready in ACM. If ACM is not available in the Amazon Region where you are creating your custom domain name, you must import a certificate to API Gateway in that Region.

To import an SSL/TLS certificate, you must provide the PEM-formatted SSL/TLS certificate body, its private key, and the certificate chain for the custom domain name.

Each certificate stored in ACM is identified by its ARN. With certificates issued by ACM, you do not have to worry about exposing any sensitive certificate details, such as the private key. To use an Amazon managed certificate for a domain name, you simply reference its ARN. 

If your application uses certificate pinning, sometimes known as SSL pinning, to pin an ACM certificate, the application might not be able to connect to your domain after Amazon renews the certificate. For more information, see [Certificate pinning problems](https://docs.amazonaws.cn/acm/latest/userguide/troubleshooting-pinning.html) in the *Amazon Certificate Manager User Guide*.

## Wildcard custom domain names


With wildcard custom domain names, you can support an almost infinite number of domain names without exceeding the [default quota](limits.md). For example, you could give each of your customers their own domain name, `customername.example.com`.

To create a wildcard custom domain name, specify a wildcard (`*`) as the first subdomain of a custom domain that represents all possible subdomains of a root domain.

For example, the wildcard custom domain name `*.example.com` results in subdomains such as `a.example.com`, `b.example.com`, and `c.example.com`. When you create the wildcard custom domain name, all its subdomains are routed by the routing mode of the wildcard domain name. To route subdomains to different APIs, you can do either of the following:
+ Use routing rules to route incoming requests to `*.example.com` to different target REST APIs using the `Host` header. For more information, see [Example 4: Routing rules for wildcard domain names](rest-api-routing-rules-examples.md#rest-api-routing-rules-examples-rule-for-wildcard-domains). 
+ Create a domain name for any subdomains that you want to route to a different endpoint. In a single Amazon account, you can have both `*.example.com` and `a.example.com`.

You can use the `$context.domainName` and `$context.domainPrefix` context variables to determine the domain name that a client used to call your API. To learn more about context variables, see [Variables for data transformations for API Gateway](api-gateway-mapping-template-reference.md).

To create a wildcard custom domain name, you must provide a certificate issued by ACM that has been validated using either the DNS or the email validation method.

**Note**  
You can't create a wildcard custom domain name if a different Amazon account has created a custom domain name that conflicts with the wildcard custom domain name. For example, if account A has created `a.example.com`, then account B can't create the wildcard custom domain name `*.example.com`.  
If account A and account B share an owner, you can contact the [Amazon Support Center](https://console.amazonaws.cn/support/home#/) to request an exception.

## Next steps for custom domain names


The following are next steps for custom domain names.

**Next steps**
+ To learn how to set your SSL/TLS certificate, see [Get certificates ready in Amazon Certificate Manager](how-to-specify-certificate-for-custom-domain-name.md).
+ To learn how to create a Regional custom domain name, see [Set up a Regional custom domain name in API Gateway](apigateway-regional-api-custom-domain-create.md).
+ To learn how to create an edge-optimized custom domain name, see [Set up an edge-optimized custom domain name in API Gateway](how-to-edge-optimized-custom-domain-name.md).
+ To learn how to migrate between Regional and edge-optimized custom domain names, see [Migrate a custom domain name to a different API endpoint type in API Gateway](apigateway-regional-api-custom-domain-migrate.md).
+ To learn how to connect API stages to a custom domain name, see [Send traffic to your APIs through your custom domain name in API Gateway](rest-api-routing-mode.md).
+ To learn how to choose a security policy for your custom domain name, see [Choose a security policy for your custom domain in API Gateway](apigateway-custom-domain-tls-version.md).
+ To learn how to turn off the default endpoint for your custom domain name, see [Disable the default endpoint for REST APIs](rest-api-disable-default-endpoint.md).
+ To learn how to use Route 53 health checks to control DNS failover from an API Gateway API, see [Configure custom health checks for DNS failover for an API Gateway API](dns-failover.md).

If this is your first time creating a custom domain name, we recommend that you start with [Get certificates ready in Amazon Certificate Manager](how-to-specify-certificate-for-custom-domain-name.md), to specify your certificate, and then [Set up a Regional custom domain name in API Gateway](apigateway-regional-api-custom-domain-create.md) to create a Regional custom domain name. 

# Get certificates ready in Amazon Certificate Manager


Before setting up a custom domain name for an API, you must have an SSL/TLS certificate ready in Amazon Certificate Manager. For more information, see the [Amazon Certificate Manager User Guide](https://docs.amazonaws.cn/acm/latest/userguide/).

## Considerations


The following are considerations for your SSL/TLS certificate.
+ If you create an edge-optimized custom domain name, API Gateway leverages CloudFront to support certificates for custom domain names. As such, the requirements and constraints of a custom domain name SSL/TLS certificate are dictated by [CloudFront](https://docs.amazonaws.cn/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html). For example, the maximum size of the public key is 2048 and the private key size can be 1024, 2048, and 4096. The public key size is determined by the certificate authority you use. Ask your certificate authority to return keys of a size different from the default length. For more information, see [Secure access to your objects](https://docs.amazonaws.cn/AmazonCloudFront/latest/DeveloperGuide/using-https.html) and [Create signed URLs and signed cookies](https://docs.amazonaws.cn/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html).
+ If you create a Regional custom domain name, the maximum size of the public key is 2048.
+ To use an ACM certificate with a Regional custom domain name, you must request or import the certificate in the same Region as your API. The certificate must cover the custom domain name.
+  To use an ACM certificate with an edge-optimized custom domain name, you must request or import the certificate in the US East (N. Virginia) – `us-east-1` Region.
+  You must have a registered domain name, such as `example.com`. You can use either [Amazon Route 53](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/) or a third-party accredited domain registrar. For a list of such registrars, see [Accredited Registrar Directory](https://www.icann.org/en/accredited-registrars) at the ICANN website. 

## To create or import an SSL/TLS certificate into ACM


The following procedures show how to create or import an SSL/TLS certificate for a domain name.

------
#### [ To request a certificate provided by ACM for a domain name ]

1. Sign in to the [Amazon Certificate Manager console](https://console.amazonaws.cn/acm).

1. Choose **Request a certificate**.

1. For **Certificate type**, choose **Request a public certificate**.

1. Choose **Next**.

1. For **Fully qualified domain name**, enter a custom domain name for your API, for example, `api.example.com`.

1. Optionally, choose **Add another name to this certificate**.

1. For **Validation method**, choose a method for validating domain ownership.

1. For **Key algorithm**, choose an encryption algorithm.

1. Choose **Request**.

1. For a valid request, a registered owner of the internet domain must consent to the request before ACM issues the certificate. If you use Route 53 to manage your public DNS records, you can update your records through the ACM console directly.

------
#### [ To import into ACM a certificate for a domain name ]

1.  Get a PEM-encoded SSL/TLS certificate for your custom domain name from a certificate authority. For a partial list of such CAs, see the [Mozilla Included CA List](https://ccadb.my.salesforce-sites.com/mozilla/IncludedCACertificateReport). 

   1. Generate a private key for the certificate and save the output to a file, using the [OpenSSL](https://www.openssl.org) toolkit at the OpenSSL website:

      ```
      openssl genrsa -out private-key-file 2048
      ```

   1. Generate a certificate signing request (CSR) with the previously generated private key, using OpenSSL:

      ```
      openssl req -new -sha256 -key private-key-file -out CSR-file
      ```

   1. Submit the CSR to the certificate authority and save the resulting certificate.

   1. Download the certificate chain from the certificate authority.
**Note**  
 If you obtain the private key in another way and the key is encrypted, you can use the following command to decrypt the key before submitting it to API Gateway for setting up a custom domain name.   

   ```
   openssl pkcs8 -topk8 -inform pem -in MyEncryptedKey.pem -outform pem -nocrypt -out MyDecryptedKey.pem
   ```

1. Upload the certificate to Amazon Certificate Manager:

   1. Sign in to the [Amazon Certificate Manager console](https://console.amazonaws.cn/acm).

   1. Choose **Import a certificate**.

   1. For **Certificate body**, enter the body of the PEM-formatted server certificate from your certificate authority. The following shows an abbreviated example of such a certificate.

      ```
      -----BEGIN CERTIFICATE-----
      EXAMPLECA+KgAwIBAgIQJ1XxJ8Pl++gOfQtj0IBoqDANBgkqhkiG9w0BAQUFADBB
      ...
      az8Cg1aicxLBQ7EaWIhhgEXAMPLE
      -----END CERTIFICATE-----
      ```

   1. For **Certificate private key**, enter your PEM-formatted certificate's private key. The following shows an abbreviated example of such a key. 

      ```
      -----BEGIN RSA PRIVATE KEY-----
      EXAMPLEBAAKCAQEA2Qb3LDHD7StY7Wj6U2/opV6Xu37qUCCkeDWhwpZMYJ9/nETO
      ...
      1qGvJ3u04vdnzaYN5WoyN5LFckrlA71+CszD1CGSqbVDWEXAMPLE
      -----END RSA PRIVATE KEY-----
      ```

   1. For **Certificate chain**, enter the PEM-formatted intermediate certificates and, optionally, the root certificate, one after the other without any blank lines. If you include the root certificate, your certificate chain must start with intermediate certificates and end with the root certificate. Use the intermediate certificates provided by your certificate authority. Do not include any intermediaries that are not in the chain of trust path. The following shows an abbreviated example. 

      ```
      -----BEGIN CERTIFICATE-----
      EXAMPLECA4ugAwIBAgIQWrYdrB5NogYUx1U9Pamy3DANBgkqhkiG9w0BAQUFADCB
      ...
      8/ifBlIK3se2e4/hEfcEejX/arxbx1BJCHBvlEPNnsdw8EXAMPLE
      -----END CERTIFICATE-----
      ```

      Here is another example.

      ```
      -----BEGIN CERTIFICATE-----
      Intermediate certificate 2
      -----END CERTIFICATE-----
      -----BEGIN CERTIFICATE-----
      Intermediate certificate 1
      -----END CERTIFICATE-----
      -----BEGIN CERTIFICATE-----
      Optional: Root certificate
      -----END CERTIFICATE-----
      ```

   1. Choose **Next**, and then choose **Next**.

------

After the certificate is successfully created or imported, make note of the certificate ARN. You need it when setting up the custom domain name.

# Set up a Regional custom domain name in API Gateway
Set up a Regional custom domain name

Use a Regional custom domain name to create a user-friendly API base URL. With a Regional custom domain name, you can map HTTP and REST API stages to the same custom domain name and use mutual TLS authentication. 

## Considerations


The following are considerations for your Regional custom domain name:
+ You must provide a Region-specific ACM certificate. This certificate must be in the same Region as your API. For more information about creating or uploading a custom domain name certificate, see [Get certificates ready in Amazon Certificate Manager](how-to-specify-certificate-for-custom-domain-name.md).
+ When you create a Regional custom domain name (or migrate one) with an ACM certificate, API Gateway creates a service-linked role in your account. The service-linked role is required to attach your ACM certificate to your Regional endpoint. The role is named **AWSServiceRoleForAPIGateway** and will have the **APIGatewayServiceRolePolicy** managed policy attached to it. For more information about use of the service-linked role, see [Using Service-Linked Roles](https://docs.amazonaws.cn/IAM/latest/UserGuide/using-service-linked-roles.html).
+ After your create your Regional custom domain name, you must create a DNS record to point the custom domain name to the Regional domain. This enables the traffic that is bound to the custom domain name to be routed to the API's Regional hostname.

  The DNS record can be the CNAME or an A Alias record. If you use Route 53 as your DNS provider, create an A Alias record. If you use a third-party DNS provider, use a CNAME record. If you use a CNAME record and create an API Gateway interface VPC endpoint with private DNS enabled for a private API, you can't resolve the custom domain name within the VPC that hosts your private API. 

## Create a Regional custom domain name


The following procedure shows how to create a Regional custom domain name. After you complete this procedure, you create a routing rule to route stages of your API to your custom domain name.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose **Create**.

1. For **Domain name**, enter a domain name.

1. For **Routing mode**, choose **Routing rules only**.

   In this routing mode, you can only send traffic from your custom domain name to your APIs by using routing rules. For more information, see [Send traffic to your APIs through your custom domain name in API Gateway](rest-api-routing-mode.md).

1. For **Minimum TLS version**, select a version.

1. Under **Endpoint configuration**, for **API endpoint type**, choose **Regional**.

1. Choose an ACM certificate. The certificate must be in the same Region as the API.

1. Choose **Create**.

------
#### [ Amazon CLI ]

The following [create-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/create-domain-name.html) command creates a custom domain name:

```
aws apigatewayv2 create-domain-name \ 
    --domain-name 'regional.example.com' \
    --domain-name-configurations CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678 \
    --routing-mode ROUTING_RULE_ONLY
```

The output will look like the following:

```
{
    "ApiMappingSelectionExpression": "$request.basepath",
    "DomainName": "regional.example.com",
    "DomainNameConfigurations": [
        {
            "ApiGatewayDomainName": "d-numh1z56v6.execute-api.us-west-2.amazonaws.com",
            "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678",
            "DomainNameStatus": "AVAILABLE",
            "EndpointType": "REGIONAL",
            "HostedZoneId": "Z2OJLYMUO9EFXC",
            "SecurityPolicy": "TLS_1_2"
        }
        "RoutingMode": "ROUTING_RULE_ONLY"
    ]
}
```

The `DomainNameConfigurations` property value returns the Regional API's hostname. You must create a DNS record to point your custom domain name to this Regional domain name. This enables the traffic that is bound to the custom domain name to be routed to this Regional API's hostname.

------

## Create a routing rule for your Regional custom domain name


After you create your custom domain name, you configure how traffic is routed from your custom domain name to your APIs. Because you set the routing mode to `ROUTING_RULE_ONLY`, you use routing rules to route incoming requests to your custom domain name to your APIs.

In this example, you create a catch-all rule that routes all incoming requests to your custom domain name to one stage of your API. You can also configure routing rules based on different header and path conditions. For more information, see [Routing rules to connect API stages to a custom domain name for REST APIs](rest-api-routing-rules.md).

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a custom domain name.

1. On the **Routing details** tab, choose **Add routing rule**.

1. Choose **Add a new condition** to add a new condition.

1. Keep this rule without any conditions. This routes all requests to your custom domain name to your target API and target stage.

1. For **Action**, use the dropdown to select your target API and target stage.

1. Choose **Next**.

1. In the priority field, enter **100**.

   API Gateway evaluates rules in priority order, from the lowest value to the highest value. Because this is a catch-all rule, you use a high priority so API Gateway can match any additional rules you create first.

1. Choose **Create routing rule**.

------
#### [ Amazon CLI ]

The following `create-routing-rule` command creates a catch-all routing rule:

```
aws apigatewayv2 create-routing-rule \
  --domain-name 'regional.example.com' \
  --priority 100 \
  --conditions  \
  --actions '[{
    "InvokeApi": {
      "ApiId": "a1b2c3",
      "Stage": "prod"
    }
  }]'
```

------

You can change the routing mode and create new rules at any time. For more information, see [Send traffic to your APIs through your custom domain name in API Gateway](rest-api-routing-mode.md).

## Create a DNS record for your Regional custom domain name


After you create your custom domain name and create base path mappings, you create a DNS record to point your custom domain name your newly created Regional domain name.

------
#### [ Amazon Web Services Management Console ]

To use the Amazon Web Services Management Console, follow the Route 53 documentation on [configuring Route 53 to route traffic to API Gateway](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/routing-to-api-gateway.html).

------
#### [ Amazon CLI ]

To configure your DNS records to map the Regional custom domain name to its hostname of the given hosted zone ID, first create a JSON file that contains the configuration for setting up a DNS record for the Regional domain name. 

The following `setup-dns-record.json` shows how to create a DNS `A` record to map a Regional custom domain name (`regional.example.com`) to its Regional hostname (`d-numh1z56v6.execute-api.us-west-2.amazonaws.com`) provisioned as part of the custom domain name creation. The `DNSName` and `HostedZoneId` properties of `AliasTarget` can take the `regionalDomainName` and `regionalHostedZoneId` values, respectively, of the custom domain name. You can also get the Regional Route 53 Hosted Zone IDs in [Amazon API Gateway Endpoints and Quotas](https://docs.amazonaws.cn/general/latest/gr/apigateway.html).

```
{
  "Changes": [
    {
      "Action": "CREATE",
      "ResourceRecordSet": {
        "Name": "regional.example.com",
        "Type": "A",
        "AliasTarget": {
          "DNSName": "d-numh1z56v6.execute-api.us-west-2.amazonaws.com",
          "HostedZoneId": "Z2OJLYMUO9EFXC",
          "EvaluateTargetHealth": false
        }
      }
    }
  ]
}
```

The following [change-resource-record-sets](https://docs.amazonaws.cn/cli/latest/reference/route53/change-resource-record-sets.html) creates a DNS record for your Regional custom domain name:

```
aws route53 change-resource-record-sets \
    --hosted-zone-id Z2OJLYMUO9EFXC \
    --change-batch file://path/to/your/setup-dns-record.json
```

Replace the`hosted-zone-id` with the Route 53 Hosted Zone ID of the DNS record set in your account. The `change-batch` parameter value points to a JSON file (*setup-dns-record.json*) in a folder (*path/to/your*).

------

# Set up an edge-optimized custom domain name in API Gateway


When you create a custom domain name for an edge-optimized API, API Gateway sets up a CloudFront distribution and a DNS record to map the API domain name to the CloudFront distribution domain name. Requests for the API are then routed to API Gateway through the mapped CloudFront distribution. This mapping is for API requests that are bound for the custom domain name to be routed to API Gateway through the mapped CloudFront distribution.

## Considerations


The following are considerations for your edge-optimized custom domain name:
+  To set up an edge-optimized custom domain name or to update its certificate, you must have a permission to update CloudFront distributions.

  The following permissions are required to update CloudFront distributions: 

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
           {
              "Sid": "AllowCloudFrontUpdateDistribution",
              "Effect": "Allow",
              "Action": [
                  "cloudfront:updateDistribution"
              ],
              "Resource": [
                  "*"
              ]
          }
      ]
  }
  ```

------
+ You must request or import a certificate for your edge-optimized custom domain name in the US East (N. Virginia) – `us-east-1` Region.
+  API Gateway supports edge-optimized custom domain names by leveraging Server Name Indication (SNI) on the CloudFront distribution. For more information on using custom domain names on a CloudFront distribution, including the required certificate format and the maximum size of a certificate key length, see [ Using Alternate Domain Names and HTTPS](https://docs.amazonaws.cn/AmazonCloudFront/latest/DeveloperGuide/using-https-alternate-domain-names.html) in the *Amazon CloudFront Developer Guide*
+ An edge-optimized custom domain names takes about 40 minutes to be ready.
+ After you create your edge-optimized custom domain name, you must create a DNS record to map the custom domain name to the CloudFront distribution name.

## Create an edge-optimize custom domain name


The following procedure describes how to create an edge-optimized custom domain name for an API.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose **Add domain name**.

1. For **Domain name**, enter a domain name.

1. For **Routing mode**, choose **API\$1MAPPING\$1ONLY**.

1. For **API endpoint type**, choose **Edge-optimized**.

1. Choose a minimum TLS version.

1. Choose an ACM certificate.

1. Choose **Add domain name**.

------
#### [ REST API ]

1. Call [domainname:create](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateDomainName.html), specifying the custom domain name and the ARN of a certificate stored in Amazon Certificate Manager.

    The successful API call returns a `201 Created` response containing the certificate ARN as well as the associated CloudFront distribution name in its payload.

1. Note the CloudFront distribution domain name shown in the output. You need it in the next step to set the custom domain's A-record alias target in your DNS.

For code examples of this REST API call, see [domainname:create](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateDomainName.html).

------

An edge-optimized custom domain names takes about 40 minutes to be ready, but the console immediately displays the associated CloudFront distribution domain name, in the form of `distribution-id.cloudfront.net`, along with the certificate ARN. In the meantime, you can create a base path mapping or a routing rule and then configure the DNS record alias to map the custom domain name to the associated CloudFront distribution domain name.

## Configure base path mapping of an API with a custom domain name as its hostname


Because you set the routing mode to `API_MAPPING_ONLY`, you can use base path mapping to use a single custom domain name as the hostname of multiple APIs. This makes an API accessible through the combination of the custom domain name and the associated base path.

For example, if in API Gateway, you created an API named `PetStore` and another API named `Dogs` and then set up a custom domain name of `api.example.com`, you can set the `PetStore` API's URL as `https://api.example.com`.

This associates the `PetStore` API with the base path of an empty string. If you set the `PetStore` API's URL as `https://api.example.com/PetStore`, this associates the `PetStore` API with the base path of `PetStore`. You can assign a base path of `MyDogList` for the `Dogs` API. The URL of `https://api.example.com/MyDogList` is then the root URL of the `Dogs` API.

To configure API mappings on multiple levels, you can only use a Regional custom domain name. Edge-optimized custom domain names are not supported. For more information, see [Use API mappings to connect API stages to a custom domain name for REST APIs](rest-api-mappings.md).

The following procedure sets up API mappings to map paths from your custom domain name to your API stages.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the API Gateway console main navigation pane.

1. Choose a custom domain name.

1. Choose **Configure API mappings**.

1. Choose **Add new mapping**.

1. Specify the **API**, **Stage**, and **Path** (optional) for the mapping.

1. Choose **Save**.

------
#### [ REST API ]

 Call [basepathmapping:create](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateBasePathMapping.html) on a specific custom domain name, specifying the `basePath`, `restApiId`, and a deployment `stage` property in the request payload.

 The successful API call returns a `201 Created` response.

For code examples of the REST API call, see [basepathmapping:create](https://docs.amazonaws.cn/apigateway/latest/api/API_CreateBasePathMapping.html).

------

For more flexibility on how you route traffic to your APIs, you can change the routing mode to `ROUTING_RULE_ONLY` or `ROUTING_RULE_THEN_API_MAPPING` and create a routing rule. For more information, see [Send traffic to your APIs through your custom domain name in API Gateway](rest-api-routing-mode.md).

## Create a DNS record for your edge-optimized custom domain name


After you initiate the creation of your edge-optimized custom domain name, set up the DNS record alias.

We recommend that you use Route 53 to create an A-record alias for your custom domain name and specify the CloudFront distribution domain name as the alias target. This means that Route 53 can route your custom domain name even if it is a zone apex. For more information, see [Choosing Between Alias and Non-Alias Resource Record Sets](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html) in the *Amazon Route 53 Developer Guide*.

 For instructions for Amazon Route 53, see [Routing traffic to an Amazon API Gateway API by using your domain name](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/routing-to-api-gateway.html) in the *Amazon Route 53 Developer Guide*.

## Rotate a certificate imported into ACM


 ACM automatically handles renewal of certificates it issues. You do not need to rotate any ACM-issued certificates for your custom domain names. CloudFront handles it on your behalf. 

 However, if you import a certificate into ACM and use it for a custom domain name, you must rotate the certificate before it expires. This involves importing a new third-party certificate for the domain name and rotate the existing certificate to the new one. You need to repeat the process when the newly imported certificate expires. Alternatively, you can request ACM to issue a new certificate for the domain name and rotate the existing one to the new ACM-issued certificate. After that, you can leave ACM and CloudFront to handle the certificate rotation for you automatically. To create or import a new ACM certificate, follow the steps in [To create or import an SSL/TLS certificate into ACM](how-to-specify-certificate-for-custom-domain-name.md#how-to-specify-certificate-for-custom-domain-name-setup).

The following procedure describes how to rotate a certificate for a domain name.

**Note**  
It takes about 40 minutes to rotate a certificate imported into ACM.

------
#### [ Amazon Web Services Management Console ]

1. Request or import a certificate in ACM.

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the API Gateway console main navigation pane.

1. Choose an edge-optimized custom domain name.

1. For **Endpoint configuration**, choose **Edit**.

1. For **ACM certificate**, select a certificate from dropdown list.

1. Choose **Save changes** to begin rotating the certificate for the custom domain name. 

------
#### [ REST API ]

 Call [domainname:update](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateDomainName.html) action, specifying the ARN of the new ACM certificate for the specified domain name. 

------
#### [ Amazon CLI ]

 The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) updates the ACM certificate for an edge-optimized domain name.

```
aws apigateway update-domain-name \
    --domain-name edge.example.com \
    --patch-operations "op='replace',path='/certificateArn',value='arn:aws-cn:acm:us-west-2:111122223333:certificate/CERTEXAMPLE123EXAMPLE'"
```

 The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) updates the ACM certificate for a Regional domain name.

```
aws apigateway update-domain-name \
    --domain-name regional.example.com \
    --patch-operations "op='replace',path='/regionalCertificateArn',value='arn:aws-cn:acm:us-west-2:111122223333:certificate/CERTEXAMPLE123EXAMPLE'"
```

------

## Call your API with custom domain names when you use a base path mapping


Calling an API with a custom domain name is the same as calling the API with its default domain name, provided that the correct URL is used.

The following examples compare and contrast a set of default URLs and corresponding custom URLs of two APIs (`udxjef` and `qf3duz`) in a specified Region (`us-east-1`), and of a given custom domain name (`api.example.com`).


| API ID | Stage | Default URL | Base path | Custom URL | 
| --- | --- | --- | --- | --- | 
| udxjef | prod | https://udxjef.execute-api.us-east-1.amazonaws.com/prod | /petstore | https://api.example.com/petstore | 
| udxjef | tst | https://udxjef.execute-api.us-east-1.amazonaws.com/tst | /petdepot | https://api.example.com/petdepot | 
| qf3duz | dev | https://qf3duz.execute-api.us-east-1.amazonaws.com/dev | /bookstore | https://api.example.com/bookstore | 
| qf3duz | tst | https://qf3duz.execute-api.us-east-1.amazonaws.com/tst | /bookstand | https://api.example.com/bookstand | 

For more flexibility on how you route traffic to your APIs, you can create a routing rule. For more information, see [Send traffic to your APIs through your custom domain name in API Gateway](rest-api-routing-mode.md).

 API Gateway supports custom domain names for an API by using [Server Name Indication (SNI)](https://en.wikipedia.org/wiki/Server_Name_Indication). You can invoke the API with a custom domain name using a browser or a client library that supports SNI. 

 API Gateway enforces SNI on the CloudFront distribution. For information on how CloudFront uses custom domain names, see [Amazon CloudFront Custom SSL](http://www.amazonaws.cn/cloudfront/custom-ssl-domains/). 

# Migrate a custom domain name to a different API endpoint type in API Gateway
Migrate custom domain names

 You can migrate your custom domain name between edge-optimized and Regional endpoints. You can't migrate a public custom domain name to a private custom domain name. You first add the new endpoint configuration type to the existing `endpointConfiguration.types` list for the custom domain name. Next, you set up a DNS record to point the custom domain name to the newly provisioned endpoint. Finally, you remove the obsolete custom domain name endpoint.

## Considerations


The following are considerations for migrating your custom domain between a Regional API endpoint and an edge-optimized API endpoint:
+ An edge-optimized custom domain name requires a certificate provided by ACM from the US East (N. Virginia) – `us-east-1` Region. This certificate is distributed to all the geographic locations.
+ A Regional custom domain name requires a certificate provided by ACM in the same Region hosting the API. You can migrate an edge-optimized custom domain name that is not in the `us-east-1` Region to a Regional custom domain name by requesting a new ACM certificate from the Region that is local to the API.
+ It might take up to 60 seconds to complete a migration between an edge-optimized custom domain name and a Regional custom domain name. The migration time also depends on when you update your DNS records.
+ You can only add an additional endpoint configuration if the endpoint access mode is set to `BASIC`. Once you have two endpoint configurations, you can't change the endpoint access mode. For more information, see [Endpoint access mode](apigateway-security-policies.md#apigateway-security-policies-endpoint-access-mode).
+ If your custom domain name uses a security policy that starts with `SecurityPolicy_`, when you add a new endpoint configuration type, the endpoint access mode is the same across both endpoint types, and you must choose a security policy that starts with `SecurityPolicy_` for the new endpoint configuration type.

## Migrate custom domain names
Migrate custom domain names

**Note**  
To complete the migration, make sure that you remove the obsolete endpoint from your custom domain name.

The following procedure shows how to migrate an edge-optimized custom domain name to a Regional custom domain name.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose an edge-optimized custom domain name.

1. For **Endpoint configuration**, choose **Edit**.

1. Choose **Add Regional endpoint**.

1. For **ACM certificate**, choose a certificate.

   The Regional certificate must be in the same Region as the Regional API.

1. Choose **Save changes**.

1. Set up a DNS record to point the Regional custom domain name to this Regional hostname. For more information, see [configuring Route 53 to route traffic to API Gateway](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/routing-to-api-gateway.html).

1. After you confirm that your DNS configuration is using the correct endpoint, you delete the edge-optimized endpoint configuration. Choose your custom domain name, and then for **Edge-optimized endpoint configuration**, choose **Delete**.

1. Confirm your choice and delete the endpoint.

------
#### [ Amazon CLI ]

The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command migrates an edge-optmized custom domain name to a Regional custom domain name:

```
aws apigateway update-domain-name \
    --domain-name 'api.example.com' \
    --patch-operations  '[ 
        { "op":"add", "path": "/endpointConfiguration/types","value": "REGIONAL" },
        { "op":"add", "path": "/regionalCertificateArn", "value": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149" }
      ]'
```

The Regional certificate must be of the same Region as the Regional API. 

The output will look like the following:

```
{
    "certificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": [
            "EDGE",
            "REGIONAL"
        ]
    },
    "regionalCertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149",
    "regionalDomainName": "d-fdisjghyn6.execute-api.us-west-2.amazonaws.com"
}
```

For the migrated Regional custom domain name, the resulting `regionalDomainName` property returns the Regional API hostname. You must set up a DNS record to point the Regional custom domain name to this Regional hostname. This enables the traffic that is bound to the custom domain name to be routed to the Regional host. 

After the DNS record is set, you can remove the edge-optimized custom domain name. The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command removes the edge-optimized custom domain name:

```
aws apigateway update-domain-name \
    --domain-name api.example.com \
    --patch-operations '[
            {"op":"remove", "path":"/endpointConfiguration/types", "value":"EDGE"},
            {"op":"remove", "path":"certificateName"},
            {"op":"remove", "path":"certificateArn"}
        ]'
```

------

The following procedure shows how to migrate an edge-optimized custom domain name that uses an enhanced security policy to a Regional custom domain name that also uses an enhanced security policy.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose an edge-optimized custom domain name.

1. For **Endpoint configuration**, choose **Edit**.

1. Choose **Add Regional endpoint**.

1. For **ACM certificate**, choose a certificate.

   The Regional certificate must be in the same Region as the Regional API.

1. For **Security policy**, choose a security policy that starts with `SecurityPolicy_`.

1. For **Endpoint access mode**, choose **Basic**.

1. Choose **Save changes**.

1. Set up a DNS record to point the Regional custom domain name to this Regional hostname. For more information, see [configuring Route 53 to route traffic to API Gateway](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/routing-to-api-gateway.html).

1. After you confirm that your DNS configuration is using the correct endpoint, you delete the edge-optimized endpoint configuration. Choose your custom domain name, and then for **Edge-optimized endpoint configuration**, choose **Delete**.

1. Confirm your choice and delete the endpoint.

------
#### [ Amazon CLI ]

The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command migrates an edge-optmized custom domain name to a Regional custom domain name:

```
aws apigateway update-domain-name \
    --domain-name 'api.example.com' \
    --patch-operations  '[ 
        { "op":"add", "path": "/endpointConfiguration/types","value": "REGIONAL" },
        { "op":"replace", "path": "/securityPolicy", "value":"SecurityPolicy_TLS13_1_3_2025_09"},
        { "op":"add", "path": "/regionalCertificateArn", "value": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149" }
      ]'
```

The Regional certificate must be of the same Region as the Regional API. 

The output will look like the following:

```
{
    "certificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": [
            "EDGE",
            "REGIONAL"
        ]
    },
    "securityPolicy": "SecurityPolicy_TLS13_1_3_2025_09",
    "endpointAccessMode": "BASIC",
    "regionalCertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149",
    "regionalDomainName": "d-fdisjghyn6.execute-api.us-west-2.amazonaws.com"
}
```

For the migrated Regional custom domain name, the resulting `regionalDomainName` property returns the Regional API hostname. You must set up a DNS record to point the Regional custom domain name to this Regional hostname. This enables the traffic that is bound to the custom domain name to be routed to the Regional host. 

After the DNS record is set, you can remove the edge-optimized custom domain name. The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command removes the edge-optimized custom domain name:

```
aws apigateway update-domain-name \
    --domain-name api.example.com \
    --patch-operations '[
            {"op":"remove", "path":"/endpointConfiguration/types", "value":"EDGE"},
            {"op":"remove", "path":"certificateName"},
            {"op":"remove", "path":"certificateArn"}
        ]'
```

------

The following procedure shows how to migrate a Regional custom domain name to an edge-optimized custom domain name.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. In the main navigation pane, choose **Custom domain names**.

1. Choose a Regional custom domain name.

1. For **Endpoint configuration**, choose **Edit**.

1. Choose **Add edge-optimized endpoint**.

1. For **ACM certificate**, choose a certificate.

    The edge-optimized domain certificate must be created in the `us-east-1` Region. 

1. Choose **Save**.

1. Set up a DNS record to point the edge-optimized custom domain name to this edge-optimized hostname. For more information, see [configuring Route 53 to route traffic to API Gateway](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/routing-to-api-gateway.html).

1. After you confirm that your DNS configuration is using the correct endpoint, you delete the Regional endpoint configuration. Choose your custom domain name, and then for **Regional endpoint configuration**, choose **Delete**.

1. Confirm your choice and delete the endpoint.

------
#### [ Amazon CLI ]

The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command migrates your Regional custom domain name to an edge-optimized custom domain name:

```
aws apigateway update-domain-name \
    --domain-name 'api.example.com' \
    --patch-operations  '[ 
        { "op":"add", "path": "/endpointConfiguration/types","value": "EDGE" },
        { "op":"add", "path": "/certificateName", "value": "edge-cert" },
	{"op":"add", "path": "/certificateArn", "value": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a"}
      ]'
```

The edge-optimized domain certificate must be created in the `us-east-1` Region. 

The output will look like the following:

```
{
    "certificateArn": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": [
            "EDGE",
            "REGIONAL"
        ]
    },
    "regionalCertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/3d881b54-851a-478a-a887-f6502760461d",
    "regionalDomainName": "d-cgkq2qwgzf.execute-api.us-east-1.amazonaws.com"
}
```

For the specified custom domain name, API Gateway returns the edge-optimized API hostname as the `distributionDomainName` property value. You must set a DNS record to point the edge-optimized custom domain name to this distribution domain name. This enables traffic that is bound to the edge-optimized custom domain name to be routed to the edge-optimized API hostname. 

After the DNS record is set, you can remove the `REGION` endpoint type of the custom domain name. The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command removes the Regional endpoint type:

```
aws apigateway update-domain-name \
    --domain-name api.example.com \
    --patch-operations '[
        {"op":"remove", "path":"/endpointConfiguration/types", value:"REGIONAL"},
        {"op":"remove", "path":"regionalCertificateArn"}
      ]'
```

The output looks like the following:

```
{
    "certificateArn": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": "EDGE"
    }
}
```

------

# Send traffic to your APIs through your custom domain name in API Gateway


When you configure the routing mode for your custom domain name, you set how incoming traffic is directed to your APIs. You send traffic to your APIs using routing rules, API mappings, or routing rules and API mappings. The following section explains when to use routing rules, when to use API mappings, and how to set the routing mode for your custom domain name.

## When to use routing rules


When you use routing rules, you direct incoming requests that match certain conditions to specific REST APIs stages. For example, a rule can route a request to the `production` stage of your `users` REST API it if contains the header `version:v1` and the base path `/users`. Use routing rules to create advanced dynamic routing topologies that support use cases like A/B testing or increasing usage of new versions of your APIs.

We recommend that when directing traffic to a REST API, you use routing rules for your custom domain name. You can recreate any API mappings by using routing rules. For more information, see [Recreate an API mapping using routing rules](rest-api-routing-rules-recreate-api-mapping.md).

For REST APIs, you can also use routing rules and API mappings together. When you use routing rules and API mappings together, API Gateway always evaluates routing rules before it evaluates any API mappings. Use routing rules and API mappings together to migrate your current custom domain names or to explore routing rules.

### Considerations for routing rules


The following considerations might impact your use of routing rules:
+ WebSocket or HTTP APIs aren't supported as target APIs for routing rules.
+ If your custom domain name has API mappings to both REST and HTTP APIs, routing rules isn't supported.
+ You can create a routing rule for a private custom domain to a private REST API. You can create a routing rule for a public custom domain to a Regional or edge-optimized API. 
+ You can't create a routing rule for a public custom domain to a private API. You can't create a routing rule for a private custom domain name to a public API.

## Choose between routing rules and API mappings


We recommend that when possible, you use routing rules. Only use API mappings to send traffic to an HTTP or WebSocket API.

# Set the routing mode for your custom domain name


You can choose which routing mode API Gateway uses to route traffic to your APIs. For more information, see [Send traffic to your APIs through your custom domain name in API Gateway](rest-api-routing-mode.md). This section discusses routing modes for custom domain names. You must set a routing mode for your custom domain name to route traffic to your APIs. The following routing modes are supported:
+ **ROUTING\$1RULE\$1THEN\$1API\$1MAPPING** – Use this mode to send traffic to your APIs with both routing rules and API mappings. In this mode, all routing rules take priority over any API mappings. For an example of this mode, see [Example 2: Routing rules and API mappings](rest-api-routing-rules-examples.md#rest-api-routing-rules-examples-rule-and-mappings). 
+ **ROUTING\$1RULE\$1ONLY** – Use this mode to only allow routing rules to send traffic to your APIs. When your custom domain name uses this mode, you can't create an API mapping, but you can use the [get-api-mappings](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/get-api-mappings.html) command to view them. API callers can’t use API mappings to access this domain name.
+ **API\$1MAPPING\$1ONLY** – Use this mode to only allow API mappings to send traffic to your APIs. When your custom domain name uses this mode, you can't create a routing rule, but you can use the `list-routing-rules` command to view them. API callers can’t use routing rules to access this domain name.

  This is the default routing mode for all your existing domain names, and any new domain names you create.

When you create a custom domain name using `apigateway`, `API_MAPPING_ONLY` is called `BASE_PATH_MAPPING_ONLY` and `ROUTING_RULE_THEN_API_MAPPING` is called `ROUTING_RULE_THEN_BASE_PATH_MAPPING`. This behavior is only present for the Amazon CLI, Amazon CloudFormation, or any SDKs, not in the Amazon Web Services Management Console.

The following procedure shows how to change the routing mode for an existing custom domain name. When you change the routing mode of your custom domain name, API callers can’t access your domain name using any unsupported routing modes.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane.

1. Choose a custom domain name.

1. For **Domain details**, choose **Edit**.

1. For **Routing mode**, choose **ROUTING\$1RULE\$1THEN\$1API\$1MAPPING**.

1. Choose **Save**.

If you change the routing mode to `ROUTING_RULE_ONLY` or `API_MAPPING_ONLY`, any API mappings or routing rules you've created are removed from the domain name details page of the console. If you change the routing mode to support either routing rules or API mappings, these resources will return.

------
#### [ Amazon CLI - apigatewayv2 ]

The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/update-domain-name.html) command updates a domain name to use the routing mode `ROUTING_RULE_THEN_API_MAPPING`:

```
aws apigatewayv2 update-domain-name \
  --domain-name 'api.example.com' \
  --routing-mode "ROUTING_RULE_THEN_API_MAPPING"
```

The output will look like the following:

```
{
"ApiMappingSelectionExpression": "$request.basepath",
"DomainName": "api.example.com",
"DomainNameArn": "arn:aws:apigateway:us-west-2::/domainnames/api.example.com",
"DomainNameConfigurations": [
  {
      "ApiGatewayDomainName": "d-abcdefg.execute-api.us-west-2.amazonaws.com",
      "CertificateArn": "arn:aws:acm:us-west-2:111122223333:certificate/abcdefg-123456-abcdefg",
      "DomainNameStatus": "AVAILABLE",
      "EndpointType": "REGIONAL",
      "HostedZoneId": "Z2OJLYMUO9EFXC",
      "SecurityPolicy": "TLS_1_2"
   }
 ],
"RoutingMode": "ROUTING_RULE_THEN_API_MAPPING",
"Tags": {}
}
```

------
#### [ Amazon CLI - apigateway ]

The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command updates a private custom domain name to use the routing mode `ROUTING_RULE_THEN_BASE_PATH_MAPPING`:

```
aws apigateway update-domain-name \
  --domain-name 'private.example.com' \
  --patch-operations "op='replace',path='/routingMode',value='ROUTING_RULE_THEN_BASE_PATH_MAPPING'"
```

The output will look like the following:

```
{
"domainName": "private.example.com",
"domainNameId": "abcd1234",
"domainNameArn": "arn:aws:apigateway:us-west-2:111122223333:/domainnames/private.example.com+abcd1234",
"certificateArn": "arn:aws:acm:us-west-2:111122223333:certificate/a1b2c3d4-5678-90ab-cdef",
"certificateUploadDate": "2024-09-10T10:31:20-07:00",
"endpointConfiguration": {
  "types": [
    "PRIVATE"
   ],
  "ipAddressType": "dualstack"
  },
"domainNameStatus": "AVAILABLE",
"securityPolicy": "TLS_1_2",
"policy": "...",
"routingMode" : "ROUTING_RULE_THEN_BASE_PATH_MAPPING"
}
```

------

# Routing rules to connect API stages to a custom domain name for REST APIs
Routing rules

A routing rule is a set of conditions that when matched, invoke an action. For example, a rule can route any incoming request to a custom domain name that contains the header `Hello:World` and contains the base path `users` to the `production` stage of a REST API.

Rules are evaluated in priority order, and if you set the routing mode to `ROUTING_RULE_THEN_API_MAPPING`, API Gateway always evaluates all routing rules before evaluating any API mappings. The following list describes how a routing rule uses conditions, actions, and priorities. 

**Conditions**  
When the conditions for a rule are met, then its actions are performed. API Gateway supports up to two header conditions and one path condition. API Gateway evaluates header conditions and base path conditions together.  
You can create a rule without any conditions. When API Gateway evaluates this rule, the action is always performed. You can create a rule without any conditions as a catch-all rule.  
For more information about header conditions, see [Match headers conditions](#rest-api-routing-rules-condition-headers). For more information about path conditions, see [Match base path conditions](#rest-api-routing-rules-condition-path). 

**Actions**  
Actions are the result of matching conditions to a routing rule. Currently, the only supported action is to invoke a stage of a REST API.  
Each rule can have one action.

**Priority**  
The priority determines what order the rules are evaluated in, from the lowest value to the highest value. Rules can't have the same priority.  
You can set the priority from 1-1,000,000. If a rule has a priority of one, API Gateway evaluates it first. We recommend that when you create a rule, you add gaps in priorities. This helps you switch the priority of rules and add new rules. For more information, see [Change the priority of a routing rule](apigateway-routing-rules-use.md#rest-api-routing-rules-change-priority).

For examples of how API Gateway evaluates routing rules, see [Examples of how API Gateway evaluates routing rules](rest-api-routing-rules-examples.md).

## API Gateway routing rule condition types


The following section describes the routing rule condition types. API Gateway only matches a rule if all conditions are true.

### Match headers conditions


When you create a header condition, you can match the header name and header glob value, such as `Hello:World`. API Gateway uses a literal match to validate match headers conditions. Your condition can use up to two headers using `AND` between them. For example, your condition can match if an incoming request contains `Hello:World` and `x-version:beta`.

The header name matching is case insensitive, but the header glob value is case sensitive. `Hello:World` will match `hello:World`, but not `Hello:world`.

For a list of restricted header values see, [Restrictions](#rest-api-routing-rules-restrictions).

#### Using wildcards with header conditions


You can only use wildcards in the header glob value, and the wildcard must be `*prefix-match`, `suffix-match*`, or `*contains*`. The following table shows examples for how to use wildcards for matching for header conditions. 


|  Header conditions  |  Requests that match the routing rule  |  Requests that don't match the routing rule  | 
| --- | --- | --- | 
|  `x-version: a*`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *a`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *a*`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *a*` and `x-version: *b*`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: b*` and `x-version: *a`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  None  | 

If you create conditions for multiple header values, such as `Accept:application/json,text/xml`, we recommend that you use `*contains*` for your header conditions and avoid creating conditions using the comma (`,`) character.

Because API Gateway matches header conditions literally, semantic matches might be routed differently. The following table shows the difference in routing rules outcomes.


|  Header conditions  |  Requests that match the routing rule  |  Requests that don't match the routing rule  | 
| --- | --- | --- | 
|  `Accept: *json`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `Accept: *json*`  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  None  | 

### Match base path conditions


When you create a base path condition, if the incoming request contains the path you specified, the rule is matched. The matching is case sensitive, so the path `New/Users` will not match with `new/users`.

You can create a base path condition for only one base path.

For a list of restricted base path conditions, [Restrictions](#rest-api-routing-rules-restrictions).

#### Strip the base path with base path conditions


When you create a base path condition, you can choose to strip the base path. When you strip the base path, API Gateway removes the incoming matched base path when it invokes the target API. This is the same behavior as when you use an API mapping. When you don't strip the base path, API Gateway forwards the entire base path to the target API. We recommend that you only strip the base path when you are recreating an API mapping.

The following table shows examples for how API Gateway evaluates the strip base path condition.


|  Condition  | Strip base path |  Incoming request  |  Result  | 
| --- | --- | --- | --- | 
|  If base path contains `PetStoreShopper/dogs`  |  True  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway calls the `GET` method of the `/` resource.  | 
|  If base path contains `PetStoreShopper/dogs`.  |  False  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway calls the `GET` method of the `PetStoreShopper/dogs` resource.  | 
|  If base path contains `PetStoreShopper`  |  True  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway calls the `GET` method of the `dogs` resource.  | 
|  If base path contains `PetStoreShopper`  |  False  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway calls the `GET` method of the `PetStoreShopper/dogs` resource.  | 
|  If base path contains `PetStoreShopper`  |  True  |  `GET https://example.com/PetStoreShopper?birds=available`  |  API Gateway calls the `GET` method of the `/` resource with the query string parameter `birds=available`.  | 
|  If base path contains `PetStoreShopper`  |  False  |  `GET https://example.com/PetStoreShopper?birds=available`  |  API Gateway calls the `GET` method of the `/PetStoreShopper` resource with the query string parameter `birds=available`.  | 

## Restrictions

+ The target API and the custom domain name must be in the same Amazon account.
+ Each rule can have one target API. 
+ You can only create a routing rule for a private custom domain name to a private API, and for a public custom domain name to a public API. You can't mix public and private resources.
+ If your custom domain name has API mappings to both REST and HTTP APIs, routing rules isn't supported.
+ The maximum priority number is 1,000,000.
+ Header restrictions:
  + Each `anyOf` condition can only contain one header value.
  + The only allowed characters for header names and header glob values are specified by [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230), which are `a-z`, `A-Z`, `0-9`, and the following special characters: `*?-!#$%&'.^_`|~`.
  + You can use a wildcard in the header glob value, but the wildcard must be `*prefix-match`, `suffix-match*`, or `*contains*`. You can't use `*` in the middle of a header glob value.
  + Wildcard header names aren't supported.
  + The header name must be less than 40 characters.
  + The header glob value must be less than 128 characters.
  + The header glob value for an infix match must be less than 40 characters.
  + The following headers aren't supported as conditions:
    + `access-control-*`
    + `apigw-*`
    + `Authorization`
    + `Connection`
    + `Content-Encoding`
    + `Content-Length`
    + `Content-Location`
    + `Forwarded`
    + `Keep-Alive`
    + `Origin`
    + `Proxy-Authenticate`
    + `Proxy-Authorization`
    + `TE`
    + `Trailers`
    + `Transfer-Encoding`
    + `Upgrade`
    + `x-amz-*`
    + `x-amzn-*`
    + `x-apigw-api-id`
    + `X-Forwarded-For`
    + `X-Forwarded-Host`
    + `X-Forwarded-Proto`
    + `x-restAPI`
    + `Via`
+ Base path restrictions:
  + The base path length must be less than 128 characters.
  + The base path must contain only letters, numbers, and the following characters: `$-_.+!*'()/`.

    These characters aren't supported for regular expressions (regex). 
  + The base path can't start or end with backslash (`\`) character.

# Examples of how API Gateway evaluates routing rules


The following section shows four examples of how API Gateway evaluates routing rules and API mappings.

## Example 1: Routing rules only


In this example, the custom domain name `https://petstore.example.com` has the routing mode set to `ROUTING_RULE_ONLY` and has the following routing rules and priorities.


|  Rule ID  |  Priority  |  Conditions  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   10   |   If request contains header: `Hello:World`   |   Target API 1   | 
|  `zzz000`  |   50   |   If request contains headers: `Accept:image/webp` and `Pet:Dog-*` and if the base path contains `PetStoreShopper`  |   Target API 2   | 
|  `efg456`  |   100   |  None  |   Target API 3   | 

The following table shows how API Gateway applies the previous routing rules to example requests.


| Request | Selected API | Explanation | 
| --- | --- | --- | 
|  `https://petstore.example.com -h "Hello:World"`  |  Target API 1  |  The request matches the routing rule `abc123`.  | 
|  `https://petstore.example.com/PetStoreShopper -h "Hello:World", "Pet:Dog-Bella", "Accept:image/webp"`  |  Target API 1  |  API Gateway evaluates all routing rules in priority order. Routing rule `abc123` has the first priority and the conditions match, so API Gateway invokes Target API 1. Although the conditions of the request also match routing rule `zzz000`, API Gateway doesn't evaluate any other routing rules after it makes a match.  | 
|  `https://petstore.example.com/PetStoreShopper -h "Pet:Dog-Bella", "Accept:image/webp"`  |  Target API 2  |  The request matches the routing rule `zzz000`. This was a match because the `Pet:Dog-Bella` was a string match to `Pet:Dog-*`  | 
|  `https://petstore.example.com/PetStoreShopper -h "Pet:Dog-Bella"`  |  Target API 3  |  The request doesn't match the routing rule `abc123`. The request doesn't match routing rule `zzz000` as all the required headers aren't present. The next priority rule matches all incoming requests, so API Gateway invokes Target API 3.  | 

## Example 2: Routing rules and API mappings


In this example, the custom domain name `https://petstore.diagram.example.com` has the routing mode set to `ROUTING_RULE_THEN_API_MAPPING` and has the following routing rules and API mappings.


|  Rule ID  |  Priority  |  Conditions  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   1   |   If request the base contains `pets`   |   Invoke the `Prod` stage of the `PetStore` API.   | 
|  `000zzz`  |   5   |   If request contains headers: `Cookie`:`*ux=beta*` and and if the base path contains `/refunds`  |   Invoke the `Beta` stage of the `Refunds` API.   | 

The following table shows API mappings for `https://petstore.backup.example.com`.


|  API mapping  |  Selected API  | 
| --- | --- | 
|   `/refunds`   |   Invoke the `Prod` stage of the `Refunds` API.   | 
|   `(none)`   |   Invoke the `Prod` stage of the `Search` API.   | 

The following diagram shows how API Gateway applies the previous routing rules and API mappings to example requests. The example requests are summarized in the table after this diagram.

The following table shows how API Gateway applies the previous routing rules and API mappings to example requests.


| Request | Selected API | Explanation | 
| --- | --- | --- | 
|  `https://petstore.diagram.com/pets`  |  The `Prod` stage of the `PetStore` API.  |  The request matches routing rule `abc123`.  | 
|  `https://petstore.diagram.example.com/refunds -h "Cookie:lang=en-us;ux=beta"`  |  The `Beta` stage of the `Refunds` API.  |  The request matches routing rule `000zzz`. The `Cookie` header contains the correct `*contains*` match and base path match for this condition.   | 
|  `https://petstore.diagram.example.com/refunds`  |  The `Prod` stage of the `Refunds` API.   |  The request doesn't have the required headers to match the routing rule `zzz000`. If API Gateway can't successfully match a routing rule, it falls back to API mappings. API Gateway can map the base path to the `Prod` stage of the `Refunds` API.   | 
|  `https://petstore.diagram.example.com/`  |  The `Prod` stage of the `Search` API.   |  The request matches the API mapping to the empty path `(none)`.  | 

## Example 3: Routing rules and API mappings with multiple level


In this example, the custom domain name `https://petstore.backup.example.com` has the routing mode set to `ROUTING_RULE_THEN_API_MAPPING` and has the following routing rules and API mappings.

The following table shows routing rules for `https://petstore.backup.example.com`.


|  Rule ID  |  Priority  |  Conditions  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   10   |   If request contains header: `Hello:World`   |   Target API 1   | 
|  `000zzz`  |   50   |   If request contains headers: `Accept`:`image/webp` and `Pet:Dog-*` and if the base path contains `PetStoreShopper`  |  Target API 2  | 

The following table shows API mappings for `https://petstore.backup.example.com`.


|  API mapping  |  Selected API  | 
| --- | --- | 
|   `PetStoreShopper`   |   Target API 3   | 
|   `PetStoreShopper/cats`   |   Target API 4   | 

The following table shows how API Gateway applies the previous routing rules and API mappings to example requests.


| Request | Selected API | Explanation | 
| --- | --- | --- | 
|  `https://petstore.example.com/PetStoreShopper -h "Accept:image/webp", "Pet:Cats" `  |  Target API 3  |  The request doesn't have the required headers to match the routing rule `zzz000`. If API Gateway can't successfully match a routing rule, it falls back to API mappings. API Gateway can map the base path to Target API 3.  | 
|  `https://petstore.example.com/PetStoreShopper/cats -h "Hello:World"`  |  Target API 1  |  The request matches routing rule `abc123`. If the routing mode is set to `ROUTING_RULE_THEN_API_MAPPING`, routing rules always take priority over API mappings.  | 
|  `https://petstore.example.com/Admin -h "Pet:Dog-Bella"`  |  None  |  The request doesn't match any routing rules or API mappings. Since there is no default routing rule, API Gateway rejects the call and sends the caller a `403 Forbidden` status code.  | 

## Example 4: Routing rules for wildcard domain names


In this example, the custom domain name `https://*.example.com` is a wildcard domain name. The wildcard supports all subdomains which route back to the same domain. The following example routing rules change this behavior to allow subdomains to route to different target APIs by using the `Host` header.

The following table shows routing rules for `https://*.example.com`.


|  Rule ID  |  Priority  |  Conditions  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   10   |   If request contains header: `Host:a.example.com`   |   Target API 1   | 
|  `000zzz`  |   50   |   If request contains headers: `Host:b.example.com`  |  Target API 2  | 
|  `efg456`  |   500   |  None  |  Target API 3  | 

The following table shows how API Gateway applies the previous routing rules to example requests.


| Request | Selected API | Explanation | 
| --- | --- | --- | 
|  `https://a.example.com`  |  Target API 1  |  The `Host` header is `a.example.com`. This request matches routing rule `abc123`.  | 
|  `https://b.example.com`  |  Target API 2  |  The `Host` header is `b.example.com`. This request matches routing rule `000zzz`.  | 
|  `https://testing.example.com`  |  Target API 3  |  This matches the catch-all routing rule `efg456`.  | 

# How to use routing rules


You can create a routing rule using the Amazon Web Services Management Console, Amazon CLI, or any Amazon SDK. After you create a rule, you can change it's priority.

## Create a routing rule


The following procedure shows how to create a routing rule for a custom domain name with a routing mode set to either `ROUTING_RULE_THEN_API_MAPPING` or `ROUTING_RULE_ONLY`.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose a custom domain name.

1. On the **Routing details** tab, choose **Add routing rule**.

1. Choose **Add a new condition** to add a new condition.

   You can add a header or base path condition. To match all incoming requests to your custom domain name, don't add a condition. 

1. For **Action**, use the dropdown to select your target API and target stage.

1. Choose **Next**.

1. In the priority field, enter a number for your priority.

   API Gateway evaluates rules in priority order, from the lowest value to the highest value.

   If you're creating a rule without a condition, we recommend that you use a high value priority.

1. Choose **Create routing rule**.

------
#### [ Amazon CLI ]

The following [create-routing-rule](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/create-routing-rule.html) command creates a routing rule with a priority of 50. In this example, API Gateway routes any incoming requests that have the headers `Hello:World` and `x-version:beta` and the base path `PetStoreShopper` to the target API `a1b2c3`.

```
 aws apigatewayv2 create-routing-rule \
  --domain-name 'api.example.com' \
  --priority 50 \
  --conditions '[
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "Hello",
            "ValueGlob": "World"
          }
        ]
      }
    },
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "x-version",
            "ValueGlob": "beta"
          }
        ]
      }
    },
    {
      "MatchBasePaths": {
        "AnyOf": [
          "PetStoreShopper"
        ]
      }
    }
  ]'\
  --actions '[
  {
    "InvokeApi": {
      "ApiId": "a1b2c3",
      "Stage": "prod"
    }
  }
 ]'
```

The output will look like the following.

```
{
    "Actions": [
        {
            "InvokeApi": {
                "ApiId": "a1b2c3",
                "Stage": "prod",
                "StripBasePath": false
            }
        }
    ],
    "Conditions": [
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "Hello",
                        "ValueGlob": "World"
                    }
                ]
            }
        },
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "x-version",
                        "ValueGlob": "beta"
                    }
                ]
            }
        },
        {
            "MatchBasePaths": {
                "AnyOf": [
                    "PetStoreShopper"
                ]
            }
        }
    ],
    "Priority": 50,
    "RoutingRuleArn": "arn:aws:apigateway:us-west-2:111122223333:/domainnames/api.example.com/routingrules/abc123",
    "RoutingRuleId": "abc123"
}
```

------

## Change the priority of a routing rule


You can change the priority of a routing rule. This takes effect immediately and might impact how API consumers invoke your custom domain names. We recommend that when you set the priorities of your routing rules, you leave gaps between rules.

For example, consider two routing rules, rule `abc123` with a priority of 50 and rule `zzz000` with a priority of 150. To change the priority of the rules so that API Gateway evaluates rule `zzz000` first, you can change the priority of rule `zzz000` to 30.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose a custom domain name.

1. On the **Routing details** tab, choose your routing rule, and then choose **Edit**. 

1. Choose **Next**.

1. For priority, enter the new priority.

1. Choose **Save changes**.

------
#### [ Amazon CLI ]

The following [put-routing-rule](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/put-routing-rule.html) command changes the priority of a routing rule `abc123`.

```
 aws apigatewayv2 put-routing-rule \
  --domain-name 'api.example.com' \
  --priority 30 \
  --routing-rule-id abc123 \
  --conditions '[
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "Hello",
            "ValueGlob": "World"
          }
        ]
      }
    },
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "x-version",
            "ValueGlob": "beta"
          }
        ]
      }
    },
    {
      "MatchBasePaths": {
        "AnyOf": [
          "PetStoreShopper"
        ]
      }
    }
  ]'\
  --actions '[
  {
    "InvokeApi": {
      "ApiId": "a1b2c3",
      "Stage": "prod"
    }
  }
 ]'
```

The output will look like the following:

```
{
    "Actions": [
        {
            "InvokeApi": {
                "ApiId": "a1b2c3",
                "Stage": "prod",
                "StripBasePath": false
            }
        }
    ],
    "Conditions": [
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "Hello",
                        "ValueGlob": "World"
                    }
                ]
            }
        },
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "x-version",
                        "ValueGlob": "beta"
                    }
                ]
            }
        },
        {
            "MatchBasePaths": {
                "AnyOf": [
                    "PetStoreShopper"
                ]
            }
        }
    ],
    "Priority": 38,
    "RoutingRuleArn": "arn:aws:apigateway:us-west-2:111122223333:/domainnames/api.example.com/routingrules/abc123",
    "RoutingRuleId": "abc123"
}
```

------

# Recreate an API mapping using routing rules


You can recreate an API mapping using routing rules. To recreate an API mapping, make sure to turn on base path striping. This preserves the behavior of API mappings. For more information, see [Strip the base path with base path conditions](rest-api-routing-rules.md#rest-api-routing-rules-condition-path-split).

The following tutorial shows how to recreate the API mapping `https:// api.example.com/orders/v2/items/categories/5` as a routing rule and how to update your access logs to log the routing rule ID API Gateway uses to send traffic to your API.

------
#### [ Amazon Web Services Management Console ]

**To set the routing mode to ROUTING\$1RULE\$1THEN\$1API\$1MAPPING**

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose your custom domain name.

1. For **Domain details**, choose **Edit**.

1. For **Routing mode**, choose **ROUTING\$1RULE\$1THEN\$1API\$1MAPPING**.

1. Choose **Save** 

After you set the routing mode, you create the routing rule.

**To create the routing rule**

1. On the **Routing details** tab, choose **Add routing rule**.

1. Choose **Add new condition** and then choose **Path**.

1. For **Path**, enter **orders/v2/items/categories/5**.

1. For **Strip base path**, choose **Active**.

1. For **Target API**, choose your target API.

1. For **Target stage**, choose your target stage.

1. Choose **Next**.

1. For priority, enter a priority.

   Even if you keep your existing API mapping, API Gateway will always use the new routing rule as routing rules always take priority over API mappings.

1. Choose **Save changes**.

After you create the routing rule, update the access log format for your stage or create a new log to confirm that API Gateway uses your routing rule to send traffic to your API.

**To update your access logs**

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose your API.

1. In the main navigation pane, choose **Stages**.

1. For **Logs and tracing**, choose **Edit**.

   If you don't have a log group, see [Set up CloudWatch logging for REST APIs in API Gateway](set-up-logging.md).

1. Add **\$1context.customDomain.routingRuleIdMatched** to your log format.

   This log group records the routing rule ID that API Gateway used to send traffic to your API. For more information, see [I can't tell how API Gateway sent traffic to my APIs](rest-api-routing-rules-troubleshoot.md#rest-api-routing-rules-logging).

1. Choose **Save**.

After you update your access logs, invoke your custom domain name. The following is an example curl command to invoke the custom domain name `https://api.example.com` with the base path `orders/v2/items/categories/5`.

```
curl "https://api.example.com/orders/v2/items/categories/5"
```

After you have successfully invoked your custom domain name, confirm that CloudWatch Logs shows the `routingRuleIdMatched`. To learn how to use the CloudWatch Logs console to view a log group, see [View API Gateway log events in the CloudWatch console](view-cloudwatch-log-events-in-cloudwatch-console.md).

------
#### [ Amazon CLI ]

1. Use the following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/update-domain-name.html) command to update the domain name `api.example.com` to use the routing mode `ROUTING_RULE_THEN_API_MAPPING`.

   ```
   aws apigatewayv2 update-domain-name \
     --domain-name 'api.example.com' \
     --routing-mode ROUTING_RULE_THEN_API_MAPPING
   ```

1. Use the following [create-routing-rule](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/create-routing-rule.html) command to create a new routing rule to recreate the API mapping `https://api.example.com/orders/v2/items/categories/5`.

   ```
   aws apigatewayv2 create-routing-rule \
     --domain-name 'api.example.com' \
     --priority 50 \
     --conditions '[
     {
       "MatchBasePaths": {
         "AnyOf": [
           "orders/v2/items/categories/5"
         ]
       }
     }
   ]' \
     --actions '[
     {
       "InvokeApi": {
         "ApiId": "a1b2c3",
         "Stage": "prod",
         "StripBasePath": true
       }
     }
   ]'
   ```

1. Use the following [update-stage](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-stage.html) command to update the access logs format to include the `$context.customDomain.routingRuleIdMatched` variable. This variable records the routing rule ID that API Gateway used to send traffic to your API. You use this log to confirm that API Gateway uses your routing rule to send traffic to your API. For more information, see [I can't tell how API Gateway sent traffic to my APIs](rest-api-routing-rules-troubleshoot.md#rest-api-routing-rules-logging).

   ```
   aws apigateway update-stage \
     --rest-api-id a1bc2c3 \
     --stage-name prod \
     --patch-operations "op=replace,path=/accessLogSettings/format,value='\$context.path \$context.customDomain.routingRuleIdMatched \$context.requestId \$context.extendedRequestId'"
   ```

   If you don't have a log group, see [Set up CloudWatch logging for REST APIs in API Gateway](set-up-logging.md).

1. Use the following example curl command to invoke your custom domain name with the base path `orders/v2/items/categories/5`.

   ```
   curl "https://api.example.com/orders/v2/items/categories/5
   ```

1. Use the following [filter-log-events](https://docs.amazonaws.cn/cli/latest/reference/logs/filter-log-events.html) command to get the log events from the log group `access-log-group-orders` that contain routing rule ID `abc123`.

   ```
   aws logs filter-log-events --log-group-name access-log-group-orders --filter-pattern abc123
   ```

    This confirms that API Gateway used the routing rule to send traffic to your API.

------

# Troubleshooting issues with routing rules


The following troubleshooting guidance might help resolve issues with your routing rules.

## I can't tell how API Gateway sent traffic to my APIs


You can use access logs for your REST API stage to log and troubleshoot your routing rules. You can view the routing rule ID that API Gateway used to send traffic to your API using the `$context.customDomain.routingRuleIdMatched` variable. To view the API mapping that API Gateway used to send traffic to your API, use the `$context.customDomain.basePathMatched` variable. 

 To log your routing rules, you need to configure [an appropriate CloudWatch Logs role](set-up-logging.md#set-up-access-logging-permissions) ARN for your account and create a log group.

The following example access log group can retrieve the relevant information for troubleshooting routing rules and API mappings. API Gateway only populates the context variable for the routing mechanism it used, otherwise the context variable is `-`. 

------
#### [ CLF ]

```
$context.path $context.customDomain.routingRuleIdMatched $context.customDomain.basePathMatched $context.requestId $context.extendedRequestId
```

------
#### [ JSON ]

```
{"requestPath": "$context.path", "routingRuleId" : "$context.customDomain.routingRuleIdMatched", "API mapping" : "$context.customDomain.basePathMatched", "requestId":"$context.requestId", "extendedRequestId":"$context.extendedRequestId"}
```

------
#### [ XML ]

```
<request id="$context.requestId"> <requestPath>$context.path</requestPath> <ruleId>$context.customDomain.routingRuleIdMatched</ruleId> <ApiMapping>$context.customDomain.basePathMatched</ApiMapping> <extendedRequestId>$context.extendedRequestId</extendedRequestId> </request>
```

------
#### [ CSV ]

```
$context.path,$context.customDomain.routingRuleIdMatched,$context.customDomain.basePathMatched,$context.requestId,$context.extendedRequestId
```

------

We also recommend that you confirm the routing mode for your custom domain name. For more information, see [Set the routing mode for your custom domain name](set-routing-mode.md).

## I can't enable routing rules on my custom domain name


You might receive the following error from API Gateway:

```
Your account doesn’t have permission to use RoutingRules.
This might be caused by an IAM policy in your account with a deny statement on BasePathMapping or ApiMapping.
To grant permission for this account to use RoutingRules, use the UpdateAccount API.
This will impact any existing IAM policies that deny access to BasePathMapping or ApiMapping.
See API Gateway documentation for further details.
```

You'll receive this error if have or had an IAM policy that denies access to [BasePathMapping](https://docs.amazonaws.cn/service-authorization/latest/reference/list_amazonapigatewaymanagement.html#amazonapigatewaymanagement-resources-for-iam-policies) or [ApiMapping](https://docs.amazonaws.cn/service-authorization/latest/reference/list_amazonapigatewaymanagementv2.html#amazonapigatewaymanagementv2-resources-for-iam-policies). When you enable routing rules for a custom domain name, although your policy will continue to deny access to `BasePathMapping` or `ApiMapping`, the same policy can be used to access `RoutingRule`. This might allow a user to change the routing behavior of your custom domain name.

For example, if you had a policy like the following:

```
{
    "Sid": "DenyCreatingApiMappings",
    "Effect": "Deny",
    "Action": "apigateway:POST",
    "Resource": [
        "arn:aws:apigateway:us-west-2::/domainnames/example.com/apimappings"
    ]
}
```

When you enable routing rules for `example.com`, this policy will continue to deny access to creating an `ApiMapping` but will not deny access to creating a `RoutingRule`.

We recommend that you audit the IAM policies in your account. The following example policy will deny access to creating `ApiMapping`, `BasePathMapping`, and `RoutingRule`:

```
{
    "Sid": "DenyCreatingBasePathMappingsApiMappings",
    "Effect": "Deny",
    "Action": "apigateway:POST",
    "Resource": [
        "arn:aws:apigateway:us-west-2::/domainnames/example.com/basepathmappings",
        "arn:aws:apigateway:us-west-2::/domainnames/example.com/apimappings"
    ]
},
{
    "Sid": "DenyCreatingRoutingRules",
    "Effect": "Deny",
    "Action": "apigateway:CreateRoutingRule",
    "Resource": [
        "arn:aws:apigateway:us-west-2:111122223333:/domainnames/example.com/routingrules/*"
    ]
}
```

After you have confirmed all your policies have been updated, you can update your API's account-level settings to enable routing rules for a Region.

Use the following [update-account](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-account.html) command to update the settings for your API's account-level settings for a Region:

```
aws apigateway update-account --patch-operations 'op=remove,path=/features,value=BlockedForRoutingRules' --region us-west-2
```

After you update your API's account-level settings, you can change the routing mode of your custom domain name. You can also continue to use IAM policies to deny access to `RoutingRules`, `ApiMapping` or `BasePathMapping`.

# Use API mappings to connect API stages to a custom domain name for REST APIs
API mappings

You use API mappings to connect API stages to a custom domain name. This sends traffic to your APIs through your custom domain name.

An API mapping specifies an API, a stage, and optionally a path to use for the mapping. For example, you can map `https://api.example.com/orders` to the `production` stage of an API.

You can map HTTP and REST API stages to the same custom domain name.

Before you create an API mapping, you must have an API, a stage, and a custom domain name. To learn more about creating a custom domain name, see [Set up a Regional custom domain name in API Gateway](apigateway-regional-api-custom-domain-create.md).

## Incoming requests to your custom domain name


When you map a custom domain name to a stage of your API, API Gateway strips the incoming base path. This removes the mapped base path from the invocation to the API. For instance, if your base path mapping was `https://api.example.com/orders/shop/5` to the `test` stage, and you used the following request, `https://api.example.com/orders/shop/5/hats`, API Gateway would invoke the `/hats` resource of the `test` stage of your API, not the `orders/shop/5/hats` resource.

## Mapping API requests


The following explains how API Gateway evaluates API mappings.

You can create an API mapping using single-level mappings, such an API mapping from `orders` to the `beta` stage of an API and an API mapping from `shipping` to the `alpha` stage of an API. For a Regional custom domain names with the TLS 1.2 security policy, API Gateway supports multi-level API mappings. You can create an API mapping from `orders/v1/items` to the `alpha` stage of an API and `orders/v2/items` to the `beta` stage of an API. When you create a mapping with multiple levels, API Gateway sends requests to the API mapping that has the longest matching path.

You can create an API mapping to the empty path `(none)`. If no path matches the request, API Gateway sends the request to the empty path `(none)`.

In this example, the custom domain name `https://api.example.com` has the following API mappings.


|  API Mapping  |  Selected API  | 
| --- | --- | 
|  `(none)`  |   API 1   | 
|   `orders`   |   API 2   | 
|  `orders/v1/items`  |   API 3   | 
|  `orders/v2/items`  |   API 4   | 
|  `orders/v1/items/categories`  |   API 5   | 

The following table shows how API Gateway applies the previous API mappings to example requests.


| Request | Selected API | Explanation | 
| --- | --- | --- | 
|  `https://api.example.com/orders`  |  API 2  |  The request exactly matches this API mapping.  | 
|  `https://api.example.com/orders/v1/items`  |  API 3  |  The request exactly matches this API mapping.  | 
|  `https://api.example.com/orders/v2/items`  |  API 4  |  The request exactly matches this API mapping.  | 
|  `https://api.example.com/orders/v1/items/123`  |  API 3  |  API Gateway chooses the mapping that has the longest matching path. The `123` at the end of the request doesn't affect the selection. See [Incoming requests to your custom domain name](#rest-api-mappings-incoming-requests).  | 
|  `https://api.example.com/orders/v2/items/categories/5`  |  API 5  |  API Gateway chooses the mapping that has the longest matching path.  | 
|  `https://api.example.com/customers`  |  API 1  |  API Gateway uses the empty mapping as a catch-all.  | 
|  `https://api.example.com/ordersandmore`  |  API 2  |  API Gateway chooses the mapping that has the longest matching prefix. For a custom domain name configured with single-level mappings, such as only `https://api.example.com/orders` and `https://api.example.com/`, API Gateway would choose `API 1`, as there is no matching path with `ordersandmore`.  | 

## Restrictions

+ In an API mapping, the custom domain name and mapped APIs must be in the same Amazon account.
+ API mappings must contain only letters, numbers, and the following characters: `$-_.+!*'()/`.
+ The maximum length for the path in an API mapping is 300 characters.
+ You can have 200 API mappings with multiple levels for each domain name. This limit doesn't include API mapping with single levels, such as `/prod`.
+ You can only map HTTP APIs to a regional custom domain name with the TLS 1.2 security policy.
+ You can't map WebSocket APIs to the same custom domain name as an HTTP API or REST API.
+ After you create your API mappings, you must create or update your DNS provider's resource record to map to your API endpoint.
+ If you create an API mappings with multiple levels, API Gateway converts all header names to lowercase.

## Create an API mapping


To create an API mapping, you must first create a custom domain name, API, and stage. Your custom domain name must have a routing mode set to either `ROUTING_RULE_THEN_API_MAPPING` or `API_MAPPING_ONLY`. For information about how to set the routing mode, see [Set the routing mode for your custom domain name](set-routing-mode.md).

For example Amazon Serverless Application Model templates that create all resources, see [Sessions With SAM](https://github.com/aws-samples/sessions-with-aws-sam/tree/master/custom-domains) on GitHub.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose **Custom domain names** from the main navigation pane. 

1. Choose a custom domain name.

1. On the **Routing details** tab, choose **Configure API mappings**.

1. Enter the **API**, **Stage**, and **Path** for the mapping.

1. Choose **Save**.

------
#### [ Amazon CLI ]

The following [create-api-mapping](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/create-api-mapping.html) command creates an API mapping. In this example, API Gateway sends requests to `api.example.com/v1/orders` to the specified API and stage.

**Note**  
To create API mappings with multiple levels, you must use `apigatewayv2`.

```
aws apigatewayv2 create-api-mapping \
    --domain-name api.example.com \
    --api-mapping-key v1/orders \
    --api-id a1b2c3d4 \
    --stage test
```

------
#### [ Amazon CloudFormation ]

The following Amazon CloudFormation example creates an API mapping.

**Note**  
To create API mappings with multiple levels, you must use `AWS::ApiGatewayV2`.

```
MyApiMapping:
  Type: 'AWS::ApiGatewayV2::ApiMapping'
  Properties:
    DomainName: api.example.com
    ApiMappingKey: 'orders/v2/items'
    ApiId: !Ref MyApi
    Stage: !Ref MyStage
```

------

# IP address types for custom domain names in API Gateway


When you create a custom domain name, you specify the type of IP addresses that can invoke your domain. You can choose IPv4 to resolve IPv4 addresses to invoke your domain, or you can choose dualstack to allow both IPv4 and IPv6 addresses to invoke your domain. We recommend that you set the IP address type to dualstack to alleviate IP space exhaustion or for your security posture. For more information about the benefits of a dualstack IP address type, see [IPv6 on Amazon](https://docs.amazonaws.cn/whitepapers/latest/ipv6-on-aws/internet-protocol-version-6.html).

You can change the IP address type by updating the endpoint configuration of your domain name.

## Considerations for IP address types


The following considerations might impact your use of IP address types.
+ The default IP address type for API Gateway custom domain names for public APIs is IPv4.
+ Private custom domain names can only have a dualstack IP address type.
+ Your custom domain name doesn't need to have the same IP address type for all APIs mapped to it. If you disable your default API endpoint, this might affect how callers can invoke your domain.

## Change the IP address type of a custom domain name


You can change the IP address type by updating the domain name's endpoint configuration. You can update the endpoint configuration by using the Amazon Web Services Management Console, the Amazon CLI, Amazon CloudFormation, or an Amazon SDK.

------
#### [ Amazon Web Services Management Console ]

**To change the IP address type of a custom domain name**

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a public custom domain name.

1. Choose **Endpoint configuration**.

1. For IP address type, select either **IPv4** or **Dualstack**.

1. Choose **Save**.

------
#### [ Amazon CLI ]

The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command updates an API to have an IP address type of dualstack:

```
aws apigateway update-domain-name \
    --domain-name dualstack.example.com \
    --patch-operations "op='replace',path='/endpointConfiguration/ipAddressType',value='dualstack'"
```

The output will look like the following:

```
{
    "domainName": "dualstack.example.com",
    "certificateUploadDate": "2025-02-04T14:46:10-08:00",
    "regionalDomainName": "d-abcd1234.execute-api.us-east-1.amazonaws.com",
    "regionalHostedZoneId": "Z3LQWSYCGH4ADY",
    "regionalCertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/a1b2c3d4-5678-90ab-cdef",
    "endpointConfiguration": {
        "types": [
            "REGIONAL"
        ],
        "ipAddressType": "dualstack"
    },
    "domainNameStatus": "AVAILABLE",
    "securityPolicy": "TLS_1_2",
    "tags": {}
}
```

------

# Choose a security policy for your custom domain in API Gateway
Choose a security policy

A *security policy* is a predefined combination of minimum TLS version and cipher suites offered by API Gateway. When your clients establish a TLS handshake to your API or custom domain name, the security policy enforces the TLS version and cipher suite accepted by API Gateway. Security policies protect your APIs and custom domain names from network security problems such as tampering and eavesdropping between a client and server.

API Gateway supports legacy security policies and enhanced security policies. `TLS_1_0` and `TLS_1_2` are legacy security policies. Use these security policies for generalized workloads, or to get started creating an API. Any policy that starts with `SecurityPolicy_` is an enhanced security policy. Use these policies for regulated workloads, advanced governance, or to use post-quantum cryptography. When you use an enhanced security policy, you must also set the endpoint access mode for additional governance. For more information, see [Endpoint access mode](apigateway-security-policies.md#apigateway-security-policies-endpoint-access-mode).

## Considerations


The following are considerations for security policies for custom domain names for REST APIs in API Gateway:
+ You can't enable mutual TLS on a domain name that uses an enhanced security policy.
+ You can't map an HTTP API to a domain name that uses an enhanced security policy.
+ If you enable multi-level base path mapping to a REST API that uses an enhanced security policy, you can’t create a base path mapping to an HTTP API for the same domain name.
+ Your API can be mapped to a custom domain name with a different security policy than your API. When you invoke that custom domain name, API Gateway uses the security policy of the API to negotiate the TLS handshake. If you disable your default API endpoint, this might affect how callers can invoke your API.
+ API Gateway supports security policies on all APIs. However, you can only choose a security policy for REST APIs. API Gateway only supports the `TLS_1_2` security policy for HTTP or WebSocket APIs.
+ API Gateway doesn't support updating a security policy for a domain name with multiple endpoint types. If you have multiple endpoint types for a domain name, delete one of them to update the security policy.

## How API Gateway applies security policies


The following example shows how API Gateway applies security policies using the `SecurityPolicy_TLS13_1_3_2025_09` security policy as an example.

The `SecurityPolicy_TLS13_1_3_2025_09` security policy accepts TLS 1.3 traffic and rejects TLS 1.2 and TLS 1.0 traffic. For TLS 1.3 traffic, the security policy accepts the following cipher suites:
+ `TLS_AES_128_GCM_SHA256`
+ `TLS_AES_256_GCM_SHA384`
+ `TLS_CHACHA20_POLY1305_SHA256`

API Gateway does not accept any other cipher suites. For instance, the security policy would reject any TLS 1.3 traffic that uses the `AES128-SHA` cipher suite.

To monitor which TLS protocol and ciphers clients used to access your API Gateway, you can use the `$context.tlsVersion` and `$context.cipherSuite` context variables in your access logs. For more information, see [Monitor REST APIs in API Gateway](rest-api-monitor.md).

To see the default security policies for all REST APIs and custom domain names, see [Default security policies](apigateway-security-policies-list.md#apigateway-security-policies-default). To see the supported security policies for all REST APIs and custom domain names, see [Supported security policies](apigateway-security-policies-list.md).

## Change your custom domain name's security policy


If you change your security policy, it takes about 15 minutes for the update to complete. You can monitor the `lastUpdateStatus` of your custom domain name. As your custom domain name updates, the `lastUpdateStatus` is `PENDING` and when it completes, it will be `AVAILABLE`.

When you use a security policy that starts with `SecurityPolicy_`, you must also turn on endpoint access mode. For more information, see [Endpoint access mode](apigateway-security-policies.md#apigateway-security-policies-endpoint-access-mode).

------
#### [ Amazon Web Services Management Console ]

**To change the security policy of a custom domain name**

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a custom domain name that sends traffic to REST APIs.

   Make sure there is only one endpoint type associated with your custom domain name.

1. Choose **Custom domain name settings**, and then choose **Edit**.

1. For **Security policy**, select a new policy.

1. For **Endpoint access mode**, choose **Strict**.

1. Choose **Save changes**.

------
#### [ Amazon CLI ]

The following [update-domain-name](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-domain-name.html) command updates a domain name to use the `SecurityPolicy_TLS13_1_3_2025_09` security policy:

```
aws apigateway update-domain-name \
    --domain-name example.com \
    --patch-operations '[
        {
            "op": "replace",
            "path": "/securityPolicy",
            "value": "SecurityPolicy_TLS13_1_3_2025_09"
        }, 
        {
            "op": "replace",
            "path": "/endpointAccessMode",
            "value": "STRICT"
        }
    ]'
```

The output will look like the following:

```
{
   "domainName": "example.com",
   "endpointConfiguration": { 
      "types": [ "REGIONAL" ], 
      "ipAddressType": "dualstack" 
   },
   "regionalCertificateArn": "arn:aws:acm:us-west-2:111122223333:certificate/a1b2c3d4-5678-90ab-cdef",
   "securityPolicy": "SecurityPolicy_TLS13_1_3_2025_09",
   "endpointAccessMode": "STRICT"
}
```

------

## Information about HTTP APIs and WebSocket APIs


For more information about HTTP APIs and WebSocket APIs, see [Security policy for HTTP APIs in API Gateway](http-api-ciphers.md) and [Security policy for WebSocket APIs in API Gateway](websocket-api-ciphers.md).

# Disable the default endpoint for REST APIs
Disable the default endpoint

By default, clients can invoke your API by using the `execute-api` endpoint that API Gateway generates for your API. To ensure that clients can access your API only by using a custom domain name, disable the default `execute-api` endpoint. Clients can still connect to your default endpoint, but they will receive a `403 Forbidden` status code. Disabling the default endpoint affects all stages of the API. This setting takes affect when you update any setting on any stage, such as updating the deployment on the stage.

The following procedure shows how to disable the default endpoint for a REST API.

------
#### [ Amazon Web Services Management Console ]

1. Sign in to the API Gateway console at [https://console.amazonaws.cn/apigateway](https://console.amazonaws.cn/apigateway).

1. Choose a REST API.

1. On the main navigation pane, choose **API settings**.

1. Choose an API.

1. On **API details**, choose **Edit**.

1. For **Default endpoint**, select **Inactive**.

1. Choose **Save changes**.

1. On the main navigation pane, choose **Resources**.

1. Choose **Deploy API**.

1. Redeploy your API to a stage or update any setting on a stage for the update to take effect.

------
#### [ Amazon CLI ]

The following [update-rest-api](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-rest-api.html) command disables the default endpoint: 

```
aws apigateway update-rest-api \
    --rest-api-id abcdef123 \
    --patch-operations op=replace,path=/disableExecuteApiEndpoint,value='True'
```

After you disable the default endpoint, you must deploy your API for the change to take effect.

The following [create-deployment](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-deployment.html) command creates a deployment and associates it with a stage:

```
aws apigateway create-deployment \
    --rest-api-id abcdef123 \
    --stage-name dev
```

------

# Configure custom health checks for DNS failover for an API Gateway API
DNS failover

You can use Amazon Route 53 health checks to control DNS failover from an API Gateway API in a primary Amazon Web Services Region to one in a secondary Region. This can help mitigate impacts in the event of a Regional issue. If you use a custom domain, you can perform failover without requiring clients to change API endpoints.

When you choose [Evaluate Target Health](https://docs.amazonaws.cn/Route53/latest/APIReference/API_AliasTarget.html#Route53-Type-AliasTarget-EvaluateTargetHealth>Evaluate Target Health) for an alias record, those records fail only when the API Gateway service is unavailable in the Region. In some cases, your own API Gateway APIs can experience interruption before that time. To control DNS failover directly, configure custom Route 53 health checks for your API Gateway APIs. For this example, you use a CloudWatch alarm that helps operators control DNS failover. For more examples and other considerations when you configure failover, see [Creating Disaster Recovery Mechanisms Using Route 53](https://amazonaws-china.com/blogs/networking-and-content-delivery/creating-disaster-recovery-mechanisms-using-amazon-route-53/) and [Performing Route 53 health checks on private resources in a VPC with Amazon Lambda and CloudWatch](https://amazonaws-china.com/blogs/networking-and-content-delivery/performing-route-53-health-checks-on-private-resources-in-a-vpc-with-aws-lambda-and-amazon-cloudwatch/).

**Topics**
+ [

## Prerequisites
](#dns-failover-prereqs)
+ [

## Step 1: Set up resources
](#dns-failover-intial-setup)
+ [

## Step 2: Initiate failover to the secondary Region
](#dns-failover-initiate)
+ [

## Step 3: Test the failover
](#dns-failover-test)
+ [

## Step 4: Return to the primary region
](#dns-failover-return)
+ [

## Next steps: Customize and test regularly
](#dns-failover-next-steps)

## Prerequisites


To complete this procedure, you must create and configure the following resources:
+ A domain name that you own.
+ An ACM certificate for that domain name in two Amazon Web Services Regions. For more info, see [Prerequisites for custom domain names](how-to-custom-domains.md#how-to-custom-domains-prerequisites).
+ A Route 53 hosted zone for your domain name. For more information, see [Working with hosted zones](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/hosted-zones-working-with.html) in the Amazon Route 53 Developer Guide.

For more information on how to create Route 53 failover DNS records for the domain names, see [Choose a routing policy](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/routing-policy.html) in the Amazon Route 53 Developer Guide. For more information on how to monitor a CloudWatch alarm, see [Monitoring a CloudWatch alarm](https://docs.amazonaws.cn/Route53/latest/DeveloperGuide/health-checks-creating-values.html#health-checks-creating-values-cloudwatch) in the Amazon Route 53 Developer Guide.

## Step 1: Set up resources


In this example, you create the following resources to configure DNS failover for your domain name:
+ API Gateway APIs in two Amazon Web Services Regions
+ API Gateway custom domain names with the same name in two Amazon Web Services Regions
+ API Gateway API mappings that connect your API Gateway APIs to the custom domain names
+ Route 53 failover DNS records for the domain names
+ A CloudWatch alarm in the secondary Region
+ A Route 53 health check based on the CloudWatch alarm in the secondary Region

First, make sure that you have all of the required resources in the primary and secondary Regions. The secondary Region should contain the alarm and health check. This way, you don't depend on the primary Region to perform failover. For example Amazon CloudFormation templates that create these resources, see [samples/primary.zip](samples/primary.zip) and [samples/secondary.zip](samples/secondary.zip).

**Important**  
Before failover to the secondary Region, make sure that all required resources are available. Otherwise, your API won't be ready for traffic in the secondary Region. 

## Step 2: Initiate failover to the secondary Region


In the following example, the standby Region receives a CloudWatch metric and initiates failover. We use a custom metric that requires operator intervention to initiate failover.

```
aws cloudwatch put-metric-data \
    --metric-name Failover \
    --namespace HealthCheck \
    --unit Count \
    --value 1 \
    --region us-west-1
```

Replace the metric data with the corresponding data for the CloudWatch alarm you configured.

## Step 3: Test the failover


Invoke your API and verify that you get a response from the secondary Region. If you used the example templates in step 1, the response changes from `{"message": "Hello from the primary Region!"}` to `{"message": "Hello from the secondary Region!"}` after failover.

```
curl https://my-api.example.com

{"message": "Hello from the secondary Region!"}
```

## Step 4: Return to the primary region


To return to the primary Region, send a CloudWatch metric that causes the health check to pass.

```
aws cloudwatch put-metric-data \
    --metric-name Failover \
    --namespace HealthCheck \
    --unit Count \
    --value 0 \
    --region us-west-1
```

Replace the metric data with the corresponding data for the CloudWatch alarm you configured.

Invoke your API and verify that you get a response from the primary Region. If you used the example templates in step 1, the response changes from `{"message": "Hello from the secondary Region!"}` to `{"message": "Hello from the primary Region!"}`.

```
curl https://my-api.example.com

{"message": "Hello from the primary Region!"}
```

## Next steps: Customize and test regularly


This example demonstrates one way to configure DNS failover. You can use a variety of CloudWatch metrics or HTTP endpoints for the health checks that manage failover. Regularly test your failover mechanisms to make sure that they work as expected, and that operators are familiar with your failover procedures.