# SpecRestApi

Represents a REST API in Amazon API Gateway, created with an OpenAPI specification.

Some properties normally accessible on

Extends: Construct › Resource › RestApiBase › SpecRestApi
Implements: IResource, IRestApi, IResourceWithPolicy, IResourceWithPolicyV2, IEnvironmentAware, IRestApiRef, IConstruct, IDependable

- CloudFormation: [`AWS::ApiGateway::RestApi`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-apigateway-restapi.html)
- L1 type: [`CfnRestApi`](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.CfnRestApi.html)
- Source: [`aws-apigateway/lib/restapi.ts`](https://github.com/aws/aws-cdk/blob/v2.275.0/packages/aws-cdk-lib/aws-apigateway/lib/restapi.ts#L815)
- Type last changed: v2.196.0 · 16 May 2025

## Example

```ts
const api = new apigateway.SpecRestApi(this, 'books-api', {
  apiDefinition: apigateway.ApiDefinition.fromAsset('path-to-file.json'),
  mode: apigateway.RestApiMode.MERGE
});
```

## Initializer

```ts
new SpecRestApi(scope: Construct, id: string, props: SpecRestApiProps)
```

## Construct Props

- `apiDefinition`: [ApiDefinition](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.ApiDefinition.html) (required) — An OpenAPI definition compatible with API Gateway.

- `binaryMediaTypes`: string[] — The list of binary media mime-types that are supported by the SpecRestApi resource, such as "image/png" or "application/octet-stream".

  **Default:** SpecRestApi supports only UTF-8-encoded text payloads.

- `cloudWatchRole`: boolean — Automatically configure an AWS CloudWatch role for API Gateway.

  **Default:** false if `@aws-cdk/aws-apigateway:disableCloudWatchRole` is enabled, true otherwise

- `cloudWatchRoleRemovalPolicy`: [RemovalPolicy](/cdk/api/v2/docs/aws-cdk-lib.RemovalPolicy.html) = RemovalPolicy.RETAIN — The removal policy applied to the AWS CloudWatch role when this resource is removed from the application.

  Requires `cloudWatchRole` to be enabled.

- `deploy`: boolean = true — Indicates if a Deployment should be automatically created for this API, and recreated when the API model (resources, methods) changes.

  Since API Gateway deployments are immutable, When this option is enabled
  (by default), an AWS::ApiGateway::Deployment resource will automatically
  created with a logical ID that hashes the API model (methods, resources
  and options). This means that when the model changes, the logical ID of
  this CloudFormation resource will change, and a new deployment will be
  created.

  If this is set, `latestDeployment` will refer to the `Deployment` object
  and `deploymentStage` will refer to a `Stage` that points to this
  deployment. To customize the stage options, use the `deployOptions`
  property.

  A CloudFormation Output will also be defined with the root URL endpoint
  of this REST API.

- `deployOptions`: [StageOptions](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.StageOptions.html) — Options for the API Gateway stage that will always point to the latest deployment when `deploy` is enabled.

  **Default:** Based on defaults of `StageOptions`.

  If `deploy` is disabled,
  this value cannot be set.

- `description`: string — A description of the RestApi construct.

  **Default:** 'Automatically created by the RestApi construct'

- `disableExecuteApiEndpoint`: boolean = false — Specifies whether clients can invoke the API using the default execute-api endpoint.

  To require that clients use a custom domain name to invoke the
  API, disable the default endpoint.

- `domainName`: [DomainNameOptions](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.DomainNameOptions.html) — Configure a custom domain name and map it to this API.

  **Default:** no domain name is defined, use `addDomainName` or directly define a `DomainName`.

- `endpointConfiguration`: [EndpointConfiguration](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.EndpointConfiguration.html) = EndpointType.EDGE — The EndpointConfiguration property type specifies the endpoint types of a REST API.

- `endpointExportName`: string — Export name for the CfnOutput containing the API endpoint.

  **Default:** when no export name is given, output will be created without export

- `endpointTypes`: [EndpointType](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.EndpointType.html)[] = EndpointType.EDGE — A list of the endpoint types of the API.

  Use this property when creating
  an API.

- `failOnWarnings`: boolean = false — Indicates whether to roll back the resource if a warning occurs while API Gateway is creating the RestApi resource.

- `minCompressionSize`: [Size](/cdk/api/v2/docs/aws-cdk-lib.Size.html) — A Size(in bytes, kibibytes, mebibytes etc) that is used to enable compression (with non-negative between 0 and 10485760 (10M) bytes, inclusive) or disable compression (when undefined) on an API.

  **Default:** Compression is disabled.

  When compression is enabled, compression or
  decompression is not applied on the payload if the payload size is
  smaller than this value. Setting it to zero allows compression for any
  payload size.

- `mode`: [RestApiMode](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.RestApiMode.html) — The Mode that determines how API Gateway handles resource updates.

  **Default:** `merge` for REST APIs created after March 29, 2021, otherwise `overwrite`

  Valid values are `overwrite` or `merge`.

  For `overwrite`, the new API definition replaces the existing one.
  The existing API identifier remains unchanged.

  For `merge`, the new API definition is merged with the existing API.

  If you don't specify this property, a default value is chosen:
  - For REST APIs created before March 29, 2021, the default is `overwrite`
  - For REST APIs created after March 29, 2021, the new API definition takes precedence, but any container types such as endpoint configurations and binary media types are merged with the existing API.

  Use the default mode to define top-level RestApi properties in addition to using OpenAPI.
  Generally, it's preferred to use API Gateway's OpenAPI extensions to model these properties.

- `parameters`: { [key: string]: string } — Custom header parameters for the request.

  **Default:** No parameters.

- `policy`: [PolicyDocument](/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyDocument.html) — A policy document that contains the permissions for this RestApi.

  **Default:** No policy.

- `restApiName`: string — A name for the API Gateway RestApi resource.

  **Default:** ID of the RestApi construct.

- `retainDeployments`: boolean = false — Retains old deployment resources when the API changes.

  This allows
  manually reverting stages to point to old deployments via the AWS
  Console.

## Properties

- `deploymentStage`: [Stage](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.Stage.html) — API Gateway stage that points to the latest deployment (if defined).

  If `deploy` is disabled, you will need to explicitly assign this value in order to
  set up integrations.

- `domainName`: [DomainName](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.DomainName.html) — The first domain name mapped to this API, if defined through the `domainName` configuration prop, or added via `addDomainName`.

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) — The environment this resource belongs to.

  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.

- `latestDeployment`: [Deployment](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.Deployment.html) — API Gateway deployment that represents the latest changes of the API.

  This resource will be automatically updated every time the REST API model changes.
  This will be undefined if `deploy` is false.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) — The tree node.

- `PROPERTY_INJECTION_ID`: string (static) — Uniquely identifies this class.

- `restApiId`: string — The ID of this API Gateway RestApi.

- `restApiName`: string — A human friendly name for this Rest API.

  Note that this is different from `restApiId`.

- `restApiRef`: [RestApiReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_apigateway.RestApiReference.html) — A reference to a RestApi resource.

- `restApiRootResourceId`: string — The resource ID of the root resource.

- `root`: [IResource](/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.IResource.html) — Represents the root resource of this API endpoint ('/').

  Resources and Methods are added to this resource.

- `stack`: [Stack](/cdk/api/v2/docs/aws-cdk-lib.Stack.html) — The stack in which this resource is defined.

- `url`: string — The deployed root URL of this REST API.

## Methods

- `addApiKey(id: string, options?: ApiKeyOptions): IApiKey` — Add an ApiKey to the deploymentStage.

- `addDomainName(id: string, options: DomainNameOptions): DomainName` — Defines an API Gateway domain name and maps it to this API.

  **Parameters**

  - `id` — The construct id.
  - `options` — custom domain options.

- `addGatewayResponse(id: string, options: GatewayResponseOptions): GatewayResponse` — Adds a new gateway response.

- `addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResult` — Adds a statement to the resource policy associated with this rest api.

  A resource policy will be automatically created upon the first call to `addToResourcePolicy`.

  Note that this does not work with imported rest api.

  **Parameters**

  - `statement` — The policy statement to add.

- `addUsagePlan(id: string, props?: UsagePlanProps): UsagePlan` — Adds a usage plan.

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  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**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — Apply the given removal policy to this resource.

  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`).

- `arnForExecuteApi(method?: string, path?: string, stage?: string): string` — Gets the "execute-api" ARN.

- `grantInvokeFromVpcEndpointsOnly(vpcEndpoints: IVpcEndpoint[]): void` — Add a resource policy that only allows API execution from a VPC Endpoint to create a private API.

  **Parameters**

  - `vpcEndpoints` — the interface VPC endpoints to grant access to.

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  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**

  - `x` — Any object.

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

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `metric(metricName: string, props?: MetricOptions): Metric` — Returns the given named metric for this API.

- `metricCacheHitCount(props?: MetricOptions): Metric` — Metric for the number of requests served from the API cache in a given period.

  Default: sum over 5 minutes

- `metricCacheMissCount(props?: MetricOptions): Metric` — Metric for the number of requests served from the backend in a given period, when API caching is enabled.

  Default: sum over 5 minutes

- `metricClientError(props?: MetricOptions): Metric` — Metric for the number of client-side errors captured in a given period.

  Default: sum over 5 minutes

- `metricCount(props?: MetricOptions): Metric` — Metric for the total number API requests in a given period.

  Default: sample count over 5 minutes

- `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.

  Default: average over 5 minutes.

- `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.

  Default: average over 5 minutes.

- `metricServerError(props?: MetricOptions): Metric` — Metric for the number of server-side errors captured in a given period.

  Default: sum over 5 minutes

- `toString(): string` — Returns a string representation of this construct.

- `urlForPath(path?: string): string` — Returns the URL for an HTTP path.

  Fails if `deploymentStage` is not set either by `deploy` or explicitly.

- `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.
