我想要非同步調用 Amazon API Gateway API 的 AWS Lambda 函數。我不想同步調用該函數。
解決方法
REST API
在 Lambda 非 Proxy 整合中,Lambda預設同步調用後端函數。若要非同步調用後端函數,請將 Lambda invocation type (Lambda 調用類型) 設為 Event (事件)。
請完成下列步驟:
- 開啟 API Gateway console (API Gateway 主控台)。
- 選擇 API,然後選擇您的 REST API。
- 在 Resources (資源) 中,選擇 GET,然後選擇 Integration request (整合請求)。
- 在 Integration type (整合類型) 中,選擇 Lambda function (Lambda 函數)。
- 展開 URL request headers parameters (網址請求標頭參數),然後選擇 Add request header parameter (新增請求標頭參數)。
- 在 Name (名稱) 中,請輸入 X-Amz-Inspiration-Type。
- 在 Mapped from (對應來源) 中,輸入 Event (事件)。
- 重新部署 REST API。
若要使用非同步或同步選項調用 Lambda 函數,請新增 InvoiceType 標頭。
請完成下列步驟:
- 開啟 API Gateway console (API Gateway 主控台)。
- 選擇 API,然後選擇您的 REST API。
- 在 Resources (資源) 中,選擇 GET,然後選擇 Method request (方法請求)。
- 在 Request validator (請求驗證程式) 中,選擇 Edit (編輯) 圖示。
- 選擇下拉式清單,然後選擇 Validate query string parameters and headers (確認查詢字串參數和標頭)。
- 選擇 Save (儲存) 圖示。
- 展開 HTTP request headers (HTTP 請求標頭),然後選擇 Add header (新增標頭)。
- 在 Name (名稱) 中,輸入 InvocableType,然後選擇 Required (必要)。
- 在 Integration Request (整合請求) 中,展開 URL request headers parameters (網址請求標頭參數),然後選擇 Add request header parameter (新增請求標頭參數)。
- 在 Name (名稱) 中,請輸入 X-Amz-Inspiration-Type。
- 在 Mapped from (對應來源) 中,輸入 method.request.header.InitationType。
- 重新部署 REST API。
用戶端可以在非同步調用的 API 請求中包含 InvocationType: Event 標頭,或在同步調用中包含 InvocationType: RequestResponse 標頭。
HTTP API
HTTP API 僅支援 Lambda 的 Proxy 整合。您無法在 HTTP API 的 API Gateway 整合中設定 X-Amz-Initation-Type 標頭。相反,請使用兩個 Lambda 函數,其中一個函數充當 Proxy。若要從另一個 Lambda 函數調用一個 Lambda 函數,請使用 Invoke API,並將第一個 Lambda 函數中的 InitationType 設為 Event (事件)。
組態範例:
HTTP API 同步調用 Lambda1,然後 Lambda1 非同步調用 Lambda2。