To connect an API Gateway to a Lambda function using CloudFormation, you can follow these steps:
- Define your API Gateway and Lambda function resources in your CloudFormation template. Here’s an example:
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: MyLambdaFunction
Runtime: python3.8
Handler: index.handler
Code:
S3Bucket: my-lambda-code-bucket
S3Key: lambda-code.zip
MyApiGateway:
Type: AWS::ApiGateway::RestApi
Properties:
Name: MyApiGateway
- Create a resource of type
AWS::ApiGateway::Resource
to define the resource path for your API Gateway:
MyApiGatewayResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref MyApiGateway
ParentId: !GetAtt MyApiGateway.RootResourceId
PathPart: myresource
- Create a method on the resource to define the HTTP method (e.g., GET, POST) and integration details:
MyApiGatewayMethod:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref MyApiGateway
ResourceId: !Ref MyApiGatewayResource
HttpMethod: GET
AuthorizationType: NONE
Integration:
Type: AWS
IntegrationHttpMethod: POST
Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations
In the above example, the Uri
property references the ARN of the Lambda function.
- Add a permission for API Gateway to invoke your Lambda function:
MyLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref MyLambdaFunction
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyApiGateway}/*/*/*
The SourceArn
property references the ARN of your API Gateway.
- Deploy your API Gateway:
MyApiGatewayDeployment:
Type: AWS::ApiGateway::Deployment
Properties:
RestApiId: !Ref MyApiGateway
- Associate the deployment with a stage (e.g., “prod”):
MyApiGatewayStage:
Type: AWS::ApiGateway::Stage
Properties:
StageName: prod
RestApiId: !Ref MyApiGateway
DeploymentId: !Ref MyApiGatewayDeployment
- After defining these resources, you can deploy your CloudFormation stack using the AWS CloudFormation service or the AWS CLI.
These steps will create an API Gateway that is connected to your Lambda function. Requests made to the API Gateway endpoint will be routed to your Lambda function for processing.