How can an aws lambda know what endpoint called it from API Gateway?

泪湿孤枕 提交于 2019-12-24 17:01:34

问题


If two different endpoints use one lambda, how can the lambda know about the parts of the URL path?

How can one lambda know it was called from /zips vs /zip?zip_code=02140 ?

I can use event["queryStringParameters"]['zip_Code'] to get the URLs query string - /zip?zip_code=02140 - from within the lambda,
but how can I know if I am called from the /zips endpoint?

I tried using event["pathStringParameters"]['zips'] which I created a test event for but that didn't work, not recognized.

I can use one lambda per specific resource but I'd like to also know other approaches and how those that use the same endpoint can have their path revealed.


回答1:


If I am following what you're asking for, namely that you have one Lambda function servicing two API Gateway endpoints, then I think you have two options:

  1. Use the path parameter
  2. Set a custom header and check that in headers

From the AWS documentation:

In Lambda proxy integration, API Gateway maps the entire client request to the input event parameter of the backend Lambda function as follows:

So given this HTTP request:

POST /testStage/hello/world?name=me HTTP/1.1
Host: gy415nuibc.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
headerName: headerValue

{
    "a": 1
}

You'll have available:

  "message": "Hello me!",
  "input": {
    "resource": "/{proxy+}",
    "path": "/hello/world",
    "httpMethod": "POST",
    "headers": {
      "Accept": "*/*",
      "Accept-Encoding": "gzip, deflate",
      ...

Here both path and headers will serve your need.

Personally, I would recommend setting a custom header. That way, no matter if your API routing changes, your Lambda will still pick it up.




回答2:


You can get the path that invoked your Lambda in the event object, under event["requestContext"]["path"]

You can see more details on what the event object contains in the documentation for using AWS Lambda with API Gateway



来源:https://stackoverflow.com/questions/57940412/how-can-an-aws-lambda-know-what-endpoint-called-it-from-api-gateway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!