简体   繁体   English

aws lambda如何知道从API网关调用它的端点?

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

If two different endpoints use one lambda, how can the lambda know about the parts of the URL path? 如果两个不同的端点使用一个lambda,那么lambda如何知道URL路径的各个部分?

How can one lambda know it was called from /zips vs /zip?zip_code=02140 ? 一个lambda如何知道它是从/zips /zip?zip_code=02140 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, 我可以使用event["queryStringParameters"]['zip_Code']从lambda中获取URL查询字符串 - /zip?zip_code=02140 -
but how can I know if I am called from the /zips endpoint? 但我怎么知道是否从/zips端点调用了我?

I tried using event["pathStringParameters"]['zips'] which I created a test event for but that didn't work, not recognized. 我尝试使用event["pathStringParameters"]['zips']我创建了一个测试事件,但是没有用,无法识别。

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. 我可以为每个特定资源使用一个lambda,但我也想知道其他方法以及那些使用相同端点的方法如何显示其路径。

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: 如果我按照你要求的那样,即你有一个两个 API网关端点提供服务的Lambda函数,那么我认为你有两个选择:

  1. Use the path parameter 使用path参数
  2. Set a custom header and check that in headers 设置自定义标头并在headers检查

From the AWS documentation : AWS文档

In Lambda proxy integration, API Gateway maps the entire client request to the input event parameter of the backend Lambda function as follows: 在Lambda代理集成中,API Gateway将整个客户端请求映射到后端Lambda函数的输入事件参数,如下所示:

So given this HTTP request: 所以给出这个HTTP请求:

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. pathheaders都可以满足您的需求。

Personally , I would recommend setting a custom header. 就个人而言 ,我建议设置一个自定义标题。 That way, no matter if your API routing changes, your Lambda will still pick it up. 这样,无论您的API路由发生变化,您的Lambda仍然会接收它。

You can get the path that invoked your Lambda in the event object, under event["requestContext"]["path"] 您可以在event["requestContext"]["path"]下获取在event对象中调用Lambda的event["requestContext"]["path"]

You can see more details on what the event object contains in the documentation for using AWS Lambda with API Gateway 您可以在使用AWS Lambda with API Gateway文档中查看有关event对象包含内容的更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM