Skip to content
18 changes: 18 additions & 0 deletions packages/@aws-cdk/aws-apigateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,24 @@ const key = api.addApiKey('ApiKey', {
});
```

You can also import an API Key by it's Id to use with a usage plan.

```ts
const api = new apigateway.RestApi(this, 'hello-api', { });
api.root.addMethod('GET'); // api must have atleast one method.

const importedKey = apigateway.ApiKey.fromApiKeyId(this, 'imported-key', '<api-key-id>');

const plan = api.addUsagePlan('UsagePlan', {
name: 'Easy',
apiKey: importedKey,
throttle: {
rateLimit: 10,
burstLimit: 2
}
});
```

In scenarios where you need to create a single api key and configure rate limiting for it, you can use `RateLimitedApiKey`.
This construct lets you specify rate limiting properties which should be applied only to the api key being created.
The API key created has the specified rate limits, such as quota and throttles, applied.
Expand Down
12 changes: 12 additions & 0 deletions packages/@aws-cdk/aws-apigateway/lib/api-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ export interface ApiKeyProps extends ApiKeyOptions {
* for Method resources that require an Api Key.
*/
export class ApiKey extends Resource implements IApiKey {

/**
* Import an ApiKey by it's Id
*/
public static fromApiKeyId(scope: Construct, id: string, apiKeyId: string): IApiKey {
class Import extends Resource implements IApiKey {
public keyId = apiKeyId;
}

return new Import(scope, id);
}

public readonly keyId: string;

constructor(scope: Construct, id: string, props: ApiKeyProps = { }) {
Expand Down
24 changes: 23 additions & 1 deletion packages/@aws-cdk/aws-apigateway/test/test.api-key.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect, haveResource, ResourcePart } from '@aws-cdk/assert';
import { expect, haveResource, haveResourceLike, ResourcePart } from '@aws-cdk/assert';
import * as cdk from '@aws-cdk/core';
import { Test } from 'nodeunit';
import * as apigateway from '../lib';
Expand Down Expand Up @@ -43,4 +43,26 @@ export = {

test.done();
},
'use an imported api key'(test: Test) {
// GIVEN
const stack = new cdk.Stack();
const api = new apigateway.RestApi(stack, 'test-api', { cloudWatchRole: false, deploy: true, deployOptions: { stageName: 'test' } });
api.root.addMethod('GET'); // api must have atleast one method.

// WHEN
const importedKey = apigateway.ApiKey.fromApiKeyId(stack, 'imported', 'KeyIdabc');
api.addUsagePlan('plan', {
apiKey: importedKey,
});

// THEN
expect(stack).to(haveResourceLike('AWS::ApiGateway::UsagePlanKey', {
KeyId: 'KeyIdabc',
KeyType: 'API_KEY',
UsagePlanId: {
Ref: 'testapiplan1B111AFF',
},
}));
test.done();
},
};