Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an optional get parameter in Serverless Lambda?

I'd like to understand if there's a quick syntax for defining a optional pathParameter in serverless (to deploy on AWS lambda).

here's what I have in my functions

functions:

 MyFunc:

    handler: handler.myFunc

    events:

      - http:

          path: /getdata/{my_id}

          method: get

          request:

            parameters:

              paths:

                my_id: true

I've found around the internet a trick to define optional param like:

          path: /getdata/{?my_id}

but it's not working for serverless. And I'm getting back this error on deploy:

 Resource's path part only allow a-zA-Z0-9._- and curly braces at the beginning and the end.

I was also wondering if changing:

 my_id: false

would be my case (but it is not)

What's then the serverless way to have my_id optional so both http call:

http://.../getdata
http://.../getdata/12345

will be managed by MyFunc?

Hope there's a cleaner solution from the need to create two different endpoints/func/lambda

Thanks

like image 908
koalaok Avatar asked Aug 08 '26 14:08

koalaok


1 Answers

Define two events.

MyFunc:
  handler: handler.myFunc
  events:
    - http:
        path: /getdata/
        method: GET
    - http:
        path: /getdata/{id}
        method: GET

Then the path variable id will work with API Gateway. In your lambda code check for event.pathParameters.id. Be careful, because event.pathParameters does not have to be defined if id is not presented.

Update:

Having

request:
  parameters:
    paths:
      id: false

in serverless yaml does not have any impact on generated CloudFormation template. You can check it yourself using sls package -p /package/dir.

like image 128
dudko Avatar answered Aug 10 '26 14:08

dudko