GET请求正常但其他请求报API Gateway内部服务器错误求助
API Gateway与Lambda请求错误修复方案
问题现象
- GET请求通过Postman发送可正常收到"GET TEST"响应
- POST、PUT、DELETE请求均返回"API Gateway : Internal server error"
- 已在API Gateway对应资源上配置好上述请求方法
关联Lambda代码(已移除数据库凭证及游标初始化代码)
import json import mysql.connector def lambda_handler(event, context): http_method = event.get('httpMethod') response = None if http_method == "GET": response = getFunction(cursor, event) elif http_method == "POST": response = postFunction(cursor, event) elif http_method == "PUT": response = putFunction(cursor, event) elif http_method == "DELETE": response = deleteFunction(cursor, event) return { "statusCode": 200, "body": json.dumps({ "event": event, "response": response }) } def getFunction(cursor, event): return "GET TEST" def postFunction(): return "POST TEST" def putFunction(): return "PUT TEST" def deleteFunction(): return "DELETE TEST"
错误根因
POST、PUT、DELETE对应的函数定义未声明参数,但在lambda_handler中调用时传入了cursor和event两个参数,导致函数调用时参数不匹配,触发运行时异常,最终被API Gateway返回500内部错误。
另外注意:当前代码中cursor变量未初始化(因移除了数据库相关代码),GET请求暂时正常是因为getFunction未实际使用该参数,但后续若需操作数据库,需补充cursor初始化逻辑,否则GET请求也会触发错误。
修复方案
方案1:调整函数定义匹配调用传参
修改POST/PUT/DELETE函数的定义,使其接收调用时传入的参数:
def postFunction(cursor, event): return "POST TEST" def putFunction(cursor, event): return "PUT TEST" def deleteFunction(cursor, event): return "DELETE TEST"
方案2:调整调用逻辑匹配函数定义
如果这些函数不需要cursor和event参数,直接修改lambda_handler中的调用代码:
if http_method == "GET": response = getFunction(cursor, event) elif http_method == "POST": response = postFunction() elif http_method == "PUT": response = putFunction() elif http_method == "DELETE": response = deleteFunction()
内容的提问来源于stack exchange,提问作者Derkel
相关产品推荐
相关产品推荐

