要实现AWS API网关集成请求设置自动化,可以使用AWS提供的云开发工具CloudFormation来定义和部署基础设施。以下是一个使用CloudFormation和AWS CLI的示例解决方案。
Resources:
MyApiGateway:
Type: AWS::ApiGateway::RestApi
Properties:
Name: MyApi
MyResource:
Type: AWS::ApiGateway::Resource
Properties:
ParentId: !GetAtt MyApiGateway.RootResourceId
RestApiId: !Ref MyApiGateway
PathPart: myresource
MyMethod:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref MyApiGateway
ResourceId: !Ref MyResource
HttpMethod: GET
AuthorizationType: NONE
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations"
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: MyLambdaFunction
Runtime: python3.8
Handler: index.handler
Code:
ZipFile: |
import json
def handler(event, context):
return {
"statusCode": 200,
"body": json.dumps({"message": "Hello from Lambda!"})
}
aws cloudformation create-stack --stack-name MyApiStack --template-body file://path/to/template.yaml --parameters ParameterKey=MyLambdaFunctionName,ParameterValue=MyLambdaFunction
aws cloudformation describe-stacks --stack-name MyApiStack --query "Stacks[0].StackStatus"
aws apigateway get-rest-apis --query "items[?name=='MyApi'].{Id:id, Name:name, Endpoint: 'https://' + id + '.execute-api.' + region + '.amazonaws.com'}" --output table
这将返回API网关的URL,可以在浏览器中访问该URL来测试API。
通过使用CloudFormation和AWS CLI,可以自动化地创建和配置API网关集成请求。可以根据实际需求修改CloudFormation模板和命令参数来适应不同的场景。