使用boto3创建集成AWS Lambda的API Gateway资源

5

我将尝试创建一个使用boto3 Python库触发Lambda函数的方法。

我正在执行以下操作:

首先,我创建资源:

new_endpoint_response = aws_apigateway.create_resource(
        restApiId = 'xxxxxxxx',
        parentId = 'xxxxxxxx',
        pathPart = event['Configure']
    )

然后,使用POST方法。
put_method_response = aws_apigateway.put_method(
        restApiId = 'xxxxxxxxxxx',
        resourceId = new_endpoint_response['id'],
        httpMethod = 'POST',
        authorizationType = 'NONE'
    )

最后,使用lambda函数将其分配给该方法。
aws_apigateway.put_integration(
        restApiId = 'xxxxxxxxxx',
        resourceId = new_endpoint_response['id'],
        httpMethod = 'POST', 
        integrationHttpMethod = 'POST',
        type = 'AWS',
        uri = 'LAMBDA ARN'
    )

这里是我遇到的问题。当我尝试进行最后一步时,总是会得到一个错误消息:
“调用PutIntegration操作时发生错误(BadRequestException):AWS ARN集成必须包含路径或操作”。
我不知道为什么会出现这种情况。根据我的搜索结果,所需的URI实际上是API调用URL,问题是我不知道这意味着什么,也不知道如何获取它。下面是示例。 arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunctionAPI.Arn}/invocations 我该如何使调用URL调用我想要的lambda函数,我该如何获取调用URL?
1个回答

10

哇喔,这个已经有一年了,所以你可能找到了其他的方法。但我会将这个放在这里,以便下一个人可以使用。目前 AWS 不是我的最爱 r/unpopularopinion

首先,我通过结合以下三种方法解决了这个问题:

  1. 首先必须存在一个 Lambda 函数,可以通过使用 AWS CLI、GUI 或者使用 boto3 函数来创建。
 lambda_client = boto3.client('lambda')
 new_lambda = lambda_client.create_function(
    FunctionName='HelloWorld',
    Runtime='nodejs12.x',
    Role='arn:aws:iam::<user_id>:role/HelloWorld',
    Handler='handler.handler',
    Code={ 'ZipFile': <zip_file_object_from_s3> },
    Description='Hello World Function',
    Publish=True,
 )

 # You can then get at least part of the invocation uri here:
 print(new_lambda['FunctionArn'])
  1. 使用boto3创建一个Rest Api
  # Create rest api
  rest_api = api_client.create_rest_api(
    name='GreatApi'
  )

  print(rest_api)

  rest_api_id = rest_api["id"]

  # Get the rest api's root id
  root_resource_id = api_client.get_resources(
    restApiId=rest_api_id
  )['items'][0]['id']
    
  # Create an api resource
  api_resource = api_client.create_resource(
    restApiId=rest_api_id,
    parentId=root_resource_id,
    pathPart='greeting'
  )

  api_resource_id = api_resource['id']

  # Add a post method to the rest api resource
  api_method = api_client.put_method(
    restApiId=rest_api_id,
    resourceId=api_resource_id,
    httpMethod='GET',
    authorizationType='NONE',
    requestParameters={
      'method.request.querystring.greeter': False
    }
  )

  print(api_method)

  put_method_res = api_client.put_method_response(
    restApiId=rest_api_id,
    resourceId=api_resource_id,
    httpMethod='GET',
    statusCode='200'
  )

  print(put_method_res)

  # The uri comes from a base lambda string with the function ARN attached to it
  arn_uri="arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:<user_id>:function:HelloWorld/invocations"
 
  put_integration = api_client.put_integration(
    restApiId=rest_api_id,
    resourceId=api_resource_id,
    httpMethod='GET',
    type='AWS',
    integrationHttpMethod='POST',
    uri=arn_uri
    credentials='arn:aws:iam::<user_id>:role/HelloWorldRole',
    requestTemplates={
      "application/json":"{\"greeter\":\"$input.params('greeter')\"}"
    },
  )

  print(put_integration)

  put_integration_response = api_client.put_integration_response(
    restApiId=rest_api_id,
    resourceId=api_resource_id,
    httpMethod='GET',
    statusCode='200',
    selectionPattern=''
  )

  print(put_integration_response)

  # this bit sets a stage 'dev' that is built off the created apigateway
  # it will look something like this:
  # https://<generated_api_id>.execute-api.<region>.amazonaws.com/dev
  deployment = api_client.create_deployment(
    restApiId=rest_api_id,
    stageName='dev',
  )

  # all that done we can then send a request to invoke our lambda function
  # https://123456.execute-api.us-east-1.amazonaws.com/dev?greeter=John
  print(deployment)

这需要更多的操作,但我认为如果没有apiGateway,你实际上无法创建资源。 等我有空时,我会构建一个示例无服务器存储库。


感谢您提供详细的代码!让我困惑的部分在于 "put_integration",我曾将 AWS 文档解释为使用 httpMethod = 'POST',但对于我的 GET Api 端点来说,正确的方法是使用 httpMethod = 'GET',并且 integrationHttpMethod = 'POST'。 - Stefan Musarra
1
对于任何也在寻找调用URL规则的人,请访问以下网址:https://<rest_api_id>.execute-api.<region>.amazonaws.com/<stagename> - TNT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接