Use path params in serverless framework 1.0

岁酱吖の 提交于 2020-01-23 05:35:12

问题


I want to use the path param /customer/{customerId} of a GET request in order to query a customer using AWS Lambda:

functions:
  createCustomer:
    handler: handler.createCustomer
    events:
    - http:
        path: customer
        method: post
  readCustomer:
    handler: handler.readCustomer
    events:
    - http:
        path: customer
        method: get

How do I have to define the path param in order to pass it to my AWS Lambda function using serverless framework 1.0?


回答1:


Define in serverless.yml

readCustomer:
  handler: handler.readCustomer
  events:
    - http:
        path: customer/{customerId}
        method: get

Access customerId in code

const customerId = event.pathParameters.customerId;



回答2:


change path name

path: customer/{customerId}

Change your handler.js file

module.exports.createCustomer= function(event, context) {

{ message: 'Go Serverless v1.0! Your function executed successfully!', event }

// you can write your logic here


};



回答3:


# Solution

  1. Define the path param - for instance customerId - in serverless.yml:

path: customer/customerId

  1. In API Gateway, under your API /customer/{customerId} go to Integration Request and create a new Body Mapping Template which responds to application/jsonand has the following content:

{ "customerId": "$input.params('customerId')" }

Now the path param customerId is passed through to the AWS Lambda function as your JSON event:

{
  "input": "{\"customerId\":\"marcel@example.com\"}",
  "response": {
    "Item": {
      "password": "abc#123",
      "email": "marcel@example.com"
    }
  }
}


来源:https://stackoverflow.com/questions/39097572/use-path-params-in-serverless-framework-1-0

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