簡體   English   中英

如何正確調用 AWS Lambda + API Gateway 的 queryStringParameters?

[英]How to correctly call queryStringParameters for AWS Lambda + API Gateway?

我正在學習使用 Lambda 函數設置 AWS API Gateway 以創建 Restful API 的教程。 我有以下代碼:

import json

def lambda_handler(event, context):
    # 1. Parse query string parameters
    transactionId = event['queryStringParameters']['transactionid']
    transactionType = event['queryStringParameters']['type']
    transactionAmounts = event['queryStringParameters']['amount']

    # 2. Construct the body of the response object
    transactionResponse = {}
    # returning values originally passed in then add separate field at the bottom
    transactionResponse['transactionid'] = transactionId
    transactionResponse['type'] = transactionType
    transactionResponse['amount'] = transactionAmounts
    transactionResponse['message'] = 'hello from lambda land'

    # 3. Construct http response object
    responseObject = {}
    responseObject['StatusCode'] = 200
    responseObject['headers'] = {}
    responseObject['headers']['Content-Type'] = 'application/json'
    responseObject['body'] = json.dumps(transactionResponse)

    # 4. Return the response object
    return responseObject

當我將 API 網關鏈接到此函數並嘗試使用查詢參數調用它時,出現錯誤:

{
"message":"Internal server error"
}

當我測試 lambda 函數時,它返回錯誤:

{
  "errorMessage": "'transactionid'",
  "errorType": "KeyError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 5, in lambda_handler\n    transactionId = event['queryStringParameters']['transactionid']\n"
  ]

有沒有人知道這里發生了什么/如何讓它工作?

只需刪除 ['queryStringParameters']。 打印事件行顯示事件 i 只是一個數組而不是鍵值對。 我碰巧正在學習相同的教程。 我還在 api 網關部分,所以我會在我的完成后更新。

當您從 lambda 函數測試時,事件中沒有 queryStringParameters,但是從 api 網關調用時它就在那里,您還可以從 api 網關進行測試,其中需要 queryStringParameters 來獲取傳遞的值。

我建議添加幾個診斷,如下所示:

import json

def lambda_handler(event, context):
    print('event:', json.dumps(event))
    print('queryStringParameters:', json.dumps(event['queryStringParameters']))

    transactionId = event['queryStringParameters']['transactionid']
    transactionType = event['queryStringParameters']['type']
    transactionAmounts = event['queryStringParameters']['amount']
    // remainder of code ...

這樣您就可以看到eventevent['queryStringParameters'] ,以確保它與您希望看到的內容相匹配。 這些將記錄在 CloudWatch Logs 中(如果您使用控制台測試事件,則可以在 AWS Lambda 控制台中看到它們)。

在您的情況下,當您的代碼希望看到transactionid (不同的拼寫)時,事實證明您的測試事件包含transactionId 因此 KeyError 異常。

問題不在於您的代碼。 它是 Lambda 函數集成設置。 請不要啟用 Lambda 函數集成設置。 您仍然可以在沒有它的情況下附加 Lambda 函數。 不勾選此項。

這是因為responseObject['StatusCode'] = 200中的拼寫錯誤

' StatusCode ' 應該是' statusCode '。

我遇到了同樣的問題,就是這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM