Package: aws-solutions-constructs.aws-openapigateway-lambda
aws-openapigateway-lambda module---Reference Documentation:https://docs.aws.amazon.com/solutions/latest/constructs/LanguagePackagePythonaws_solutions_constructs.aws_openapigateway_lambdaTypescript@aws-solutions-constructs/aws-openapigateway-lambdaJavasoftware.amazon.awsconstructs.services.openapigatewaylambdaOverviewThis AWS Solutions Construct implements an Amazon API Gateway REST API defined by an OpenAPI specification file connected to an AWS Lambda function.Here is a minimal deployable pattern definition:Typescriptimport{Stack,StackProps}from'aws-cdk-lib';import{Construct}from'constructs';import{OpenApiGatewayToLambda}from'@aws-solutions-constructs/aws-openapigateway-lambda';import{Asset}from'aws-cdk-lib/aws-s3-assets';import*aspathfrom'path';import*aslambdafrom'aws-cdk-lib/aws-lambda';constapiDefinitionAsset=newAsset(this,'ApiDefinitionAsset',{path:path.join(__dirname,'openapispec.yaml')});newOpenApiGatewayToLambda(this,'OpenApiGatewayToLambda',{apiDefinitionAsset,apiIntegrations:[{id:'MessagesHandler',lambdaFunctionProps:{runtime:lambda.Runtime.NODEJS_18_X,handler:'index.handler',code:lambda.Code.fromAsset(`${__dirname}/messages-lambda`),}}]});Pythonfromaws_solutions_constructs.aws_openapigateway_lambdaimportApiGatewayToLambdafromaws_cdkimport(Stack)importaws_cdk.aws_s3_assetsass3_assetsimportaws_cdk.aws_lambdaaslambda_fromconstructsimportConstructfrom.api_definitionimportApiDefinitionapi_definition_asset=s3_assets.Asset(self,"ApiDefinitionAsset",path="openapispec.yaml")api_integration=ApiDefinition("MessagesHandler",(runtime=lambda_.Runtime.NODEJS_18_X,handler="index.handler",code=lambda_.Code.from_inline("exports.handler = handler.toString()")))ApiGatewayToLambda(self,"OpenApiGatewayToLambda",api_definition_asset=api_definition_asset,api_integrations=[api_integration])Javaimportsoftware.amazon.awscdk.services.lambda.Code;importsoftware.amazon.awscdk.services.lambda.FunctionProps;importsoftware.amazon.awscdk.services.s3.assets.Asset;importsoftware.amazon.awscdk.services.s3.assets.AssetProps;importsoftware.amazon.awsconstructs.services.openapigatewaylambda.ApiIntegration;importsoftware.amazon.awsconstructs.services.openapigatewaylambda.OpenApiGatewayToLambda;importsoftware.amazon.awsconstructs.services.openapigatewaylambda.OpenApiGatewayToLambdaProps;importsoftware.constructs.Construct;importsoftware.amazon.awscdk.Stack;importsoftware.amazon.awscdk.StackProps;importjava.util.Collections;import staticsoftware.amazon.awscdk.services.lambda.Runtime.NODEJS_18_X;finalAssetapiDefinitionAsset=newAsset(this,"ApiDefinition",AssetProps.builder().path("openapispec.yaml").build());finalApiIntegrationapiIntegration=ApiIntegration.builder().id("MessagesHandler").lambdaFunctionProps(newFunctionProps.Builder().runtime(NODEJS_18_X).code(Code.fromAsset("lambda")).handler("index.handler").build()).build();newOpenApiGatewayToLambda(this,"OpenApiGatewayToLambda",OpenApiGatewayToLambdaProps.builder().apiDefinitionAsset(apiDefinitionAsset).apiIntegrations(Collections.singletonList(apiIntegration)).build());Pattern Construct PropsNameTypeDescriptionapiGatewayProps?apigateway.RestApiBasePropsOptional user-provided props to override the default props for the API.apiDefinitionBucket?s3.IBucketS3 Bucket where the OpenAPI spec file is located. When specifying this property,apiDefinitionKeymust also be specified.apiDefinitionKey?stringS3 Object name of the OpenAPI spec file. When specifying this property,apiDefinitionBucketmust also be specified.apiDefinitionAsset?aws_s3_assets.AssetLocal file asset of the OpenAPI spec file.apiIntegrationsApiIntegration[]One or more key-value pairs that contain an id for the api integration and either an existing lambda function or an instance of the LambdaProps. Please see theOverview of how the OpenAPI file transformation workssection below for more usage details.logGroupProps?logs.LogGroupPropsUser provided props to override the default props for for the CloudWatchLogs LogGroup.Pattern PropertiesNameTypeDescriptionapiLambdaFunctionsApiLambdaFunction[]Returns an array of ApiLambdaFunction objects, where each has anidof theapiIntegrationand the correspondinglambda.Functionthat it maps to.apiGatewayapi.SpecRestApiReturns an instance of the API Gateway REST API created by the pattern.apiGatewayCloudWatchRole?iam.RoleReturns an instance of the iam.Role created by the construct for API Gateway for CloudWatch access.apiGatewayLogGrouplogs.LogGroupReturns an instance of the LogGroup created by the construct for API Gateway access logging to CloudWatch.Overview of how the OpenAPI file transformation worksThis construct automatically transforms an incoming OpenAPI Definition (residing locally or in S3) by auto-populating theurifields of thex-amazon-apigateway-integrationintegrations with the resolved value of the backing lambda functions. It does so by allowing the user to specify theapiIntegrationsproperty and then correlates it with the api definition.Looking at an example - a user creates an instantiation ofapiIntegrationsthat specifies one integration namedMessagesHandlerthat passes in a set oflambda.FunctionPropsand a second integration namedPhotosHandlerthat passes in an existinglambda.Function:constapiIntegrations:ApiIntegration[]=[{id:'MessagesHandler',lambdaFunctionProps:{runtime:lambda.Runtime.NODEJS_18_X,handler:'index.handler',code:lambda.Code.fromAsset(`${__dirname}/messages-lambda`),}},{id:'PhotosHandler',existingLambdaObj:newlambda.Function(this,'PhotosLambda',{runtime:lambda.Runtime.NODEJS_18_X,handler:'index.handler',code:lambda.Code.fromAsset(`${__dirname}/photos-lambda`),})}]And a corresponding api definition withGETandPOSTmethods on a/messagesresource and aGETmethod on a/photosresource.openapi: "3.0.1"
info:
  title: "api"
  version: "2023-02-20T20:46:08Z"
paths:
  /messages:
    get:
      x-amazon-apigateway-integration:
        httpMethod: "POST"
        uri: MessagesHandler
        passthroughBehavior: "when_no_match"
        type: "aws_proxy"
    post:
      x-amazon-apigateway-integration:
        httpMethod: "POST"
        uri: MessagesHandler
        passthroughBehavior: "when_no_match"
        type: "aws_proxy"
  /photos:
    get:
      x-amazon-apigateway-integration:
        httpMethod: "POST"
        uri: PhotosHandler
        passthroughBehavior: "when_no_match"
        type: "aws_proxy"When the construct is created or updated, it will overwrite theMessagesHandlerstring with the fully resolved lambda proxy uri of theMessagesHandlerLambdaFunction, e.g.,arn:${Aws.PARTITION}:apigateway:${Aws.REGION}:lambda:path/2015-03-31/functions/${messagesLambda.functionArn}/invocations, and similarly for thePhotosHandlerstring andPhotosHandlerLambdaFunction, resulting in a valid OpenAPI spec file that is then passed to theSpecRestApiconstruct.For more information on specifying an API with OpenAPI, please see theOpenAPI SpecificationApiIntegration DetailsThis construct defines a custom type,ApiIntegration, that is specified as a required prop. The type has a required property,id, and two optional propertiesexistingLambdaObjandlambdaFunctionProps. Theidproperty is used to map the corresponding lambda function being defined with the placeholder string in the OpenAPI template file, and is not a CDK construct ID. Exactly one ofexistingLambdaObjorlambdaFunctionPropsmust be specified or the construct will throw an error.Default settingsOut of the box implementation of the Construct without any override will set the following defaults:Amazon API GatewayDeploy an edge-optimized API endpointEnable CloudWatch logging for API GatewayConfigure least privilege access IAM role for API GatewayEnable X-Ray TracingAWS Lambda FunctionConfigure limited privilege access IAM roles for Lambda functionsEnable reusing connections with Keep-Alive for NodeJs Lambda functionsEnable X-Ray TracingSet Environment VariablesAWS_NODEJS_CONNECTION_REUSE_ENABLED (for Node 10.x and higher functions)Architecture© Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.