Ana Paula
Ana Paula

Reputation: 9507

How to pass and retrieve multiple parameters in lambda function?

I'm currently developing a REST API using the serverless framework with python and dynamoDB. I would like to know how I can pass and retrieve parameters in my lambda function. My configuration on serverless.xml looks like:

getNearestConvenios:
  handler: src/controllers/convenio_controller.get_nearest_convenios
  events:
    - http:
        path: convenios/nearest
        method: get
        cors: True
        request:
          template:
            application/json: '{ "lat" : "$input.params(''lat'')",  "long" : "$input.params(''long'')"}'

and I'm trying to retrieve the parameters like this:

def get_nearest_convenios(event, context):
  try:
    parameters = event['pathParameters']
    convenios = service.get_nearest_convenios(parameters['lat'], parameters['long'])
    return http.ok(convenios)
  except Exception as ex:
    logger.warn("WARNING: Request id: {0}, Error: {1}, Info: {2}".format(context.aws_request_id, type(ex), ex.args))
    return http.bad_request(str(ex))

I followed the Custom Request Templates provided on the official documentation, but I had no success until now. Also, in CloudWatch the following error is being showed:

    [WARNING]   2020-08-14T09:04:11.783Z    3c9222b2-4601-4460-ba7c-3cd89ba3b04b    WARNING: Request id: 3c9222b2-4601-4460-ba7c-3cd89ba3b04b, Error: <class 'TypeError'>, Info: ("'NoneType' object is not subscriptable",)

Upvotes: 2

Views: 2899

Answers (1)

Arun Kamalanathan
Arun Kamalanathan

Reputation: 8603

you haven't specified any integration type in your lambda, therefore it will use the default lambda-proxy integration type. In Lambda proxy integration, when a client submits an API request, API Gateway passes to the integrated Lambda function the raw request as-is. You cannot use mapping templates with lambda-proxy integration. If you would like to transform your request or response, you can choose lambda integration without proxy.

You are using an HTTP GET. Therefore you can pass the data as a query string or path parameters.

  • Query string: you pass the data in the url for example http://api.example.com/Books?id=1. The query string parameters can be accessed inside the lambda as event. queryStringParameters

  • Path Parameters: you can define a parameter in your serverless template as below. then you can access the path parameters inside the lambda like event.pathParameters

    getNearestConvenios:
    handler: src/controllers/convenio_controller.get_nearest_convenios/{parameter}
    events:
      - http:
          path: convenios/nearest
          method: get
          cors: True
    

Reference: Lambda Proxy Integration

Upvotes: 2

Related Questions