Skip to content

Instantly share code, notes, and snippets.

@MarkiyanPyts
Created November 16, 2023 10:52
Show Gist options
  • Save MarkiyanPyts/e99bfb820dba21e7e320d1bf3e5ee214 to your computer and use it in GitHub Desktop.
Save MarkiyanPyts/e99bfb820dba21e7e320d1bf3e5ee214 to your computer and use it in GitHub Desktop.
Example of API key protected AWS API
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { aws_lambda_nodejs, aws_apigateway } from 'aws-cdk-lib'
import * as path from "path";
export class AwsCdkExampleStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const test_lambda = new aws_lambda_nodejs.NodejsFunction(this, 'test-lambda', {
entry: path.join(
__dirname,
`./functions/test_lambda/index.ts`
), // accepts .js, .jsx, .cjs, .mjs, .ts, .tsx, .cts and .mts files
handler: 'handler', // defaults to 'handler'
});
const api_gateway = new aws_apigateway.RestApi(this, `my-api_gateway`);
const test_api_resource = api_gateway.root.addResource('test');
test_api_resource.addMethod('GET', new aws_apigateway.LambdaIntegration(test_lambda), {
apiKeyRequired: true,
// authorizationType: aws_apigateway.AuthorizationType.IAM,
requestParameters: {
'method.request.header.x-api-key': true,
},
});
const usagePlan = api_gateway.addUsagePlan('UsagePlan', {
name: 'UsagePlan',
// throttle: {
// rateLimit: 100,
// burstLimit: 200,
// },
});
usagePlan.addApiStage({ stage: api_gateway.deploymentStage })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment