Michael Durrant
Michael Durrant

Reputation: 96484

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?

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.

Upvotes: 1

Views: 866

Answers (2)

bishop
bishop

Reputation: 39394

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.

Upvotes: 3

Anon Coward
Anon Coward

Reputation: 10825

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

Upvotes: 1

Related Questions