Skip to content
v2.274.0

Stage L2 construct ​

Example ​

ts
// production stage
const prodLogGroup = new logs.LogGroup(this, "PrdLogs");
const api = new apigateway.RestApi(this, 'books', {
  deployOptions: {
    accessLogDestination: new apigateway.LogGroupLogDestination(prodLogGroup),
    accessLogFormat: apigateway.AccessLogFormat.jsonWithStandardFields(),
  },
});
const deployment = new apigateway.Deployment(this, 'Deployment', {api});

// development stage
const devLogGroup = new logs.LogGroup(this, "DevLogs");
new apigateway.Stage(this, 'dev', {
  deployment,
  accessLogDestination: new apigateway.LogGroupLogDestination(devLogGroup),
  accessLogFormat: apigateway.AccessLogFormat.jsonWithStandardFields({
    caller: false,
    httpMethod: true,
    ip: true,
    protocol: true,
    requestTime: true,
    resourcePath: true,
    responseLength: true,
    status: true,
    user: true,
  }),
});
python
# production stage
prod_log_group = logs.LogGroup(self, "PrdLogs")
api = apigateway.RestApi(self, "books",
    deploy_options=apigateway.StageOptions(
        access_log_destination=apigateway.LogGroupLogDestination(prod_log_group),
        access_log_format=apigateway.AccessLogFormat.json_with_standard_fields()
    )
)
deployment = apigateway.Deployment(self, "Deployment", api=api)

# development stage
dev_log_group = logs.LogGroup(self, "DevLogs")
apigateway.Stage(self, "dev",
    deployment=deployment,
    access_log_destination=apigateway.LogGroupLogDestination(dev_log_group),
    access_log_format=apigateway.AccessLogFormat.json_with_standard_fields(
        caller=False,
        http_method=True,
        ip=True,
        protocol=True,
        request_time=True,
        resource_path=True,
        response_length=True,
        status=True,
        user=True
    )
)
java
// production stage
LogGroup prodLogGroup = new LogGroup(this, "PrdLogs");
RestApi api = RestApi.Builder.create(this, "books")
        .deployOptions(StageOptions.builder()
                .accessLogDestination(new LogGroupLogDestination(prodLogGroup))
                .accessLogFormat(AccessLogFormat.jsonWithStandardFields())
                .build())
        .build();
Deployment deployment = Deployment.Builder.create(this, "Deployment").api(api).build();

// development stage
LogGroup devLogGroup = new LogGroup(this, "DevLogs");
Stage.Builder.create(this, "dev")
        .deployment(deployment)
        .accessLogDestination(new LogGroupLogDestination(devLogGroup))
        .accessLogFormat(AccessLogFormat.jsonWithStandardFields(JsonWithStandardFieldProps.builder()
                .caller(false)
                .httpMethod(true)
                .ip(true)
                .protocol(true)
                .requestTime(true)
                .resourcePath(true)
                .responseLength(true)
                .status(true)
                .user(true)
                .build()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
// production stage
var prodLogGroup = new LogGroup(this, "PrdLogs");
var api = new RestApi(this, "books", new RestApiProps {
    DeployOptions = new StageOptions {
        AccessLogDestination = new LogGroupLogDestination(prodLogGroup),
        AccessLogFormat = AccessLogFormat.JsonWithStandardFields()
    }
});
var deployment = new Deployment(this, "Deployment", new DeploymentProps { Api = api });

// development stage
var devLogGroup = new LogGroup(this, "DevLogs");
new Stage(this, "dev", new StageProps {
    Deployment = deployment,
    AccessLogDestination = new LogGroupLogDestination(devLogGroup),
    AccessLogFormat = AccessLogFormat.JsonWithStandardFields(new JsonWithStandardFieldProps {
        Caller = false,
        HttpMethod = true,
        Ip = true,
        Protocol = true,
        RequestTime = true,
        ResourcePath = true,
        ResponseLength = true,
        Status = true,
        User = true
    })
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// production stage
prodLogGroup := logs.NewLogGroup(this, jsii.String("PrdLogs"))
api := apigateway.NewRestApi(this, jsii.String("books"), &RestApiProps{
	DeployOptions: &StageOptions{
		AccessLogDestination: apigateway.NewLogGroupLogDestination(prodLogGroup),
		AccessLogFormat: apigateway.AccessLogFormat_JsonWithStandardFields(),
	},
})
deployment := apigateway.NewDeployment(this, jsii.String("Deployment"), &DeploymentProps{
	Api: Api,
})

// development stage
devLogGroup := logs.NewLogGroup(this, jsii.String("DevLogs"))
apigateway.NewStage(this, jsii.String("dev"), &StageProps{
	Deployment: Deployment,
	AccessLogDestination: apigateway.NewLogGroupLogDestination(devLogGroup),
	AccessLogFormat: apigateway.AccessLogFormat_*JsonWithStandardFields(&JsonWithStandardFieldProps{
		Caller: jsii.Boolean(false),
		HttpMethod: jsii.Boolean(true),
		Ip: jsii.Boolean(true),
		Protocol: jsii.Boolean(true),
		RequestTime: jsii.Boolean(true),
		ResourcePath: jsii.Boolean(true),
		ResponseLength: jsii.Boolean(true),
		Status: jsii.Boolean(true),
		User: jsii.Boolean(true),
	}),
})

Initializer ​

ts
new Stage(scope: Construct, id: string, props: StageProps)
python
Stage(scope: Construct, id: str, props: StageProps)
java
new Stage(Construct scope, String id, StageProps props)
csharp
new Stage(Construct scope, string id, StageProps props)
go
NewStage(Scope Construct, Id *string, Props StageProps)

Construct Props ​

accessLogDestinationoptionalIAccessLogDestinationaccess_log_destinationoptionalIAccessLogDestinationaccessLogDestinationoptionalIAccessLogDestinationAccessLogDestinationoptionalIAccessLogDestinationAccessLogDestinationoptionalIAccessLogDestination#
The CloudWatch Logs log group or Firehose delivery stream where to write access logs.

Default: No destination

accessLogFormatoptionalAccessLogFormataccess_log_formatoptionalAccessLogFormataccessLogFormatoptionalAccessLogFormatAccessLogFormatoptionalAccessLogFormatAccessLogFormatoptionalAccessLogFormat#
A single line format of access logs of data, as specified by selected $content variables.

Default: Common Log Format

The format must include either AccessLogFormat.contextRequestId() or AccessLogFormat.contextExtendedRequestId().

cacheClusterEnabledoptionalbooleancache_cluster_enabledoptionalboolcacheClusterEnabledoptionalBooleanCacheClusterEnabledoptionalboolCacheClusterEnabledoptional*bool#
Indicates whether cache clustering is enabled for the stage.

Default: Disabled for the stage.

cacheClusterSizeoptionalstringcache_cluster_sizeoptionalstrcacheClusterSizeoptionalStringCacheClusterSizeoptionalstringCacheClusterSizeoptional*string= 0.5#
The stage's cache cluster size.
cacheDataEncryptedoptionalbooleancache_data_encryptedoptionalboolcacheDataEncryptedoptionalBooleanCacheDataEncryptedoptionalboolCacheDataEncryptedoptional*bool= false#
Indicates whether the cached responses are encrypted.
cacheTtloptionalDurationcache_ttloptionalDurationcacheTtloptionalDurationCacheTtloptionalDurationCacheTtloptionalDuration= Duration.minutes(5)#
Specifies the time to live (TTL), in seconds, for cached responses.

The higher the TTL, the longer the response will be cached.

cachingEnabledoptionalbooleancaching_enabledoptionalboolcachingEnabledoptionalBooleanCachingEnabledoptionalboolCachingEnabledoptional*bool#
Specifies whether responses should be cached and returned for requests.

Default: Caching is Disabled.

A cache cluster must be enabled on the stage for responses to be cached.

clientCertificateIdoptionalstringclient_certificate_idoptionalstrclientCertificateIdoptionalStringClientCertificateIdoptionalstringClientCertificateIdoptional*string= None.#
The identifier of the client certificate that API Gateway uses to call your integration endpoints in the stage.
dataTraceEnabledoptionalbooleandata_trace_enabledoptionalbooldataTraceEnabledoptionalBooleanDataTraceEnabledoptionalboolDataTraceEnabledoptional*bool= false#
Specifies whether data trace logging is enabled for this method.

When enabled, API gateway will log the full API requests and responses. This can be useful to troubleshoot APIs, but can result in logging sensitive data. We recommend that you don't enable this feature for production APIs.

deploymentDeploymentdeploymentDeploymentdeploymentDeploymentDeploymentDeploymentDeploymentDeploymentrequired#
The deployment that this stage points to [disable-awslint:ref-via-interface].
descriptionoptionalstringdescriptionoptionalstrdescriptionoptionalStringDescriptionoptionalstringDescriptionoptional*string#
A description of the purpose of the stage.

Default: No description.

documentationVersionoptionalstringdocumentation_versionoptionalstrdocumentationVersionoptionalStringDocumentationVersionoptionalstringDocumentationVersionoptional*string#
The version identifier of the API documentation snapshot.

Default: No documentation version.

loggingLeveloptionalMethodLoggingLevellogging_leveloptionalMethodLoggingLevelloggingLeveloptionalMethodLoggingLevelLoggingLeveloptionalMethodLoggingLevelLoggingLeveloptionalMethodLoggingLevel= Off#
Specifies the logging level for this method, which effects the log entries pushed to Amazon CloudWatch Logs.
methodOptionsoptional{ [key: string]: MethodDeploymentOptions }method_optionsoptionaltyping.Mapping[str, MethodDeploymentOptions]methodOptionsoptionalMap<String, MethodDeploymentOptions>MethodOptionsoptionalIDictionary<string, MethodDeploymentOptions>MethodOptionsoptional*map[string]MethodDeploymentOptions#
Method deployment options for specific resources/methods.

Default: Common options will be used.

These will override common options defined in StageOptions#methodOptions.

metricsEnabledoptionalbooleanmetrics_enabledoptionalboolmetricsEnabledoptionalBooleanMetricsEnabledoptionalboolMetricsEnabledoptional*bool= false#
Specifies whether Amazon CloudWatch metrics are enabled for this method.
stageNameoptionalstringstage_nameoptionalstrstageNameoptionalStringStageNameoptionalstringStageNameoptional*string= "prod"#
The name of the stage, which API Gateway uses as the first path segment in the invoked Uniform Resource Identifier (URI).
throttlingBurstLimitoptionalnumberthrottling_burst_limitoptionalint | floatthrottlingBurstLimitoptionalNumberThrottlingBurstLimitoptionaldoubleThrottlingBurstLimitoptional*float64#
Specifies the throttling burst limit.

Default: No additional restriction.

The total rate of all requests in your AWS account is limited to 5,000 requests.

throttlingRateLimitoptionalnumberthrottling_rate_limitoptionalint | floatthrottlingRateLimitoptionalNumberThrottlingRateLimitoptionaldoubleThrottlingRateLimitoptional*float64#
Specifies the throttling rate limit.

Default: No additional restriction.

The total rate of all requests in your AWS account is limited to 10,000 requests per second (rps).

tracingEnabledoptionalbooleantracing_enabledoptionalbooltracingEnabledoptionalBooleanTracingEnabledoptionalboolTracingEnabledoptional*bool= false#
Specifies whether Amazon X-Ray tracing is enabled for this method.
variablesoptional{ [key: string]: string }variablesoptionaltyping.Mapping[str, str]variablesoptionalMap<String, String>VariablesoptionalIDictionary<string, string>Variablesoptional*map[string]*string#
A map that defines the stage variables.

Default: No stage variables.

Variable names must consist of alphanumeric characters, and the values must match the following regular expression: [A-Za-z0-9-._~:/?#&=,]+.

Properties ​

The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
restApiIRestApirest_apiIRestApirestApiIRestApiRestApiIRestApiRestApiIRestApirequired#
RestApi to which this stage is associated.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
stageArnstringstage_arnstrstageArnStringStageArnstringStageArn*stringrequired#
Returns the resource ARN for this stage:.

arn:aws:apigateway:{region}::/restapis/{restApiId}/stages/{stageName}

Note that this is separate from the execute-api ARN for methods and resources within this stage.

stageNamestringstage_namestrstageNameStringStageNamestringStageName*stringrequired#
Name of this stage.
stageRefStageReferencestage_refStageReferencestageRefStageReferenceStageRefStageReferenceStageRefStageReferencerequired#
A reference to a Stage resource.

Methods ​

addApiKey(id: string, options?: ApiKeyOptions): IApiKeydef add_api_key(self, id: str, options: typing.Optional[ApiKeyOptions] = None) -> IApiKeypublic IApiKey addApiKey(String id, ApiKeyOptions options)public IApiKey AddApiKey(string id, ApiKeyOptions? options = null)func AddApiKey(Id *string, Options ApiKeyOptions) IApiKey#
Add an ApiKey to this stage.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromStageAttributes(scope: Construct, id: string, attrs: StageAttributes): IStage@staticmethod def from_stage_attributes(scope: Construct, id: str, attrs: StageAttributes) -> IStagepublic static IStage fromStageAttributes(Construct scope, String id, StageAttributes attrs)public static IStage FromStageAttributes(Construct scope, string id, StageAttributes attrs)func FromStageAttributes(Scope Construct, Id *string, Attrs StageAttributes) IStagestatic#
Import a Stage by its attributes.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#
Returns the given named metric for this stage.
metricCacheHitCount(props?: MetricOptions): Metricdef metric_cache_hit_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCacheHitCount(MetricOptions props)public Metric MetricCacheHitCount(MetricOptions? props = null)func MetricCacheHitCount(Props MetricOptions) Metric#
Metric for the number of requests served from the API cache in a given period.
metricCacheMissCount(props?: MetricOptions): Metricdef metric_cache_miss_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCacheMissCount(MetricOptions props)public Metric MetricCacheMissCount(MetricOptions? props = null)func MetricCacheMissCount(Props MetricOptions) Metric#
Metric for the number of requests served from the backend in a given period, when API caching is enabled.
metricClientError(props?: MetricOptions): Metricdef metric_client_error(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricClientError(MetricOptions props)public Metric MetricClientError(MetricOptions? props = null)func MetricClientError(Props MetricOptions) Metric#
Metric for the number of client-side errors captured in a given period.
metricCount(props?: MetricOptions): Metricdef metric_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCount(MetricOptions props)public Metric MetricCount(MetricOptions? props = null)func MetricCount(Props MetricOptions) Metric#
Metric for the total number API requests in a given period.
metricIntegrationLatency(props?: MetricOptions): Metricdef metric_integration_latency(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricIntegrationLatency(MetricOptions props)public Metric MetricIntegrationLatency(MetricOptions? props = null)func MetricIntegrationLatency(Props MetricOptions) Metric#
Metric for the time between when API Gateway relays a request to the backend and when it receives a response from the backend.
metricLatency(props?: MetricOptions): Metricdef metric_latency(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricLatency(MetricOptions props)public Metric MetricLatency(MetricOptions? props = null)func MetricLatency(Props MetricOptions) Metric#
The time between when API Gateway receives a request from a client and when it returns a response to the client.

The latency includes the integration latency and other API Gateway overhead.

metricServerError(props?: MetricOptions): Metricdef metric_server_error(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricServerError(MetricOptions props)public Metric MetricServerError(MetricOptions? props = null)func MetricServerError(Props MetricOptions) Metric#
Metric for the number of server-side errors captured in a given period.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
urlForPath(path?: string): stringdef url_for_path(self, path: typing.Optional[str] = None) -> strpublic String urlForPath(String path)public string UrlForPath(string? path = null)func UrlForPath(Path *string) *string#
Returns the invoke URL for a certain path.
1 parameter

Parameters

  • pathpathpathpathPath — The resource path.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.