使用 CDK 将 API 网关连接到 Lambda 时出现问题

药水

我正在使用 Python CDK 部署由 API 调用触发的 Lambda 函数。这是我的代码:

app.py

#!/usr/bin/env python3
import os

from aws_cdk import core

from cvsg_app_bff.usermanagement import UserManagementStack

app = core.App()
UserManagementStack(app, "UserManagementStack")

app.synth()

我的堆栈:

class UserManagementStack(core.Stack):

def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
    super().__init__(scope, construct_id, **kwargs)

    # Lambda functions
    create_new_user: _lambda.Function = _lambda.Function(self, "newUserLambdaHandler",
                                                            runtime=_lambda.Runtime.PYTHON_3_8,
                                                            handler="usermanagement.create_new_user",
                                                            code=_lambda.Code.from_asset("lambda_functions")
                                                            )

    # API gateway setup
    user_apis = api_gw.LambdaRestApi(self, 'UserManagementAPIs', handler=create_new_user, proxy=False)

    user_apis.root.resource_for_path('user').add_method('POST', api_gw.LambdaIntegration(create_new_user))

带有 Lambda 函数的文件:

def format_return(status_code, response_body):
    response = {
        'statusCode': status_code,
        'body': response_body
    }
    print("Response: ", str(response))
    return response


def is_admin(event):
    # todo: not implemented yet!
    return True


def get_event_body(event):
    print(json.dumps(event))
    return json.loads(event["body"])


def create_new_user(event, context):
    request_body = get_event_body(event)
    if is_admin(event):
        return format_return(200, request_body)
    else:
        return format_return(403, "Not Unauthorised for this operation")

当我部署并命中端点时,我收到一条带有此消息的 502 Bad Gateway 响应

{
    "message": "Internal server error"
}

我查看了 CloudWatch 日志,我可以看到format_response方法中打印的正确响应,但来自客户端的响应始终是 502。

如何让 API 网关返回正确的响应?

特尼特

看起来您的问题是您的 Lambda 函数返回了不正确的响应。API 网关通过 Lambda 代理集成调用的 Lambda 函数需要返回以下格式的 JSON 对象:

{
    "isBase64Encoded": True|False,
    "statusCode": <status code>,
    "headers": {
        "header-name": "header-value",
        # ...
    },
    "body": "{\"your\":\"data\"}" # <--- MUST be a string, NOT an object
}

您的create_new_user函数返回format_return(200, request_body),其中request_bodyget_event_body, 返回的结果json.loads(返回dict,而不是字符串)。

get_event_body像这样改变应该可以解决问题:

def get_event_body(event):
    print(json.dumps(event))
    return json.dumps(event["body"])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将 api 网关连接到 Kinesis 流

使用Api网关连接到ElastiCache群集

将网关连接到AWS IoT

使用Flask将Docker容器连接到App Engine中的PostgreSQL时出现问题

使用MTP将Android ICS连接到Ubuntu时出现问题

使用 Spring Boot 将 Cloud Run Application 连接到 Cloud SQL 时出现问题

使用 redux 将图像从 react 发布到 Django Rest API 时出现问题

使用 Laravel 和 Guzzle 包将 Web API 发送到 Spotify 时出现问题

您如何将API网关指向CDK中的lambda别名?

Spring Integration将网关连接到服务激活器

将Snowflake连接到DataFactory时出现问题

使用DataContext文件和webConfig文件将Web App与localdb连接时出现问题

在JPA中使用连接表时,我的post api中出现问题

使用C#连接到Oracle时出现问题

是否可以在连接到 API 网关的 Lambda 上使用 AWS KPL

错误:意外的服务器响应:尝试通过Amazon API网关Websocket API连接到Lambda函数时出现502

将文件发送到API时出现问题

使用Active Collab v5通过API将文件附加到任务时出现问题

使用 MSDN Microsoft.Xml.XMLGen( XmlSampleGenerator API) 将复杂类型的 XSD 转换为 XML 时出现问题

API 网关代理与 CDK 中的 lambda 函数集成

AWS-CDK的跨栈Lambda和API网关权限

如何使用CDK python将请求参数传递给Api网关的httpintegration

使用 Graph API 创建 AD 组时出现问题

使用FileReader API打开文件时出现问题

使用ClientResponse Jersey调用Rest API时出现问题

使用configparser传递API凭证时出现问题

使用Docusign API获取JWT令牌时出现问题

在Google磁盘API中使用凭据时出现问题

使用 Swift 从 API 解析 JSON 数据时出现问题