I have been trying and searched online, but was not able to find a response. Is it possible to achieve the following using Serverless Framework:
I want to use the get.handler
that has the code to the following definition for both getting one item and getting all the items. So:
api.example.com/items/
I retrieve all the itemsapi.example.com/items/1234
I retrieve item with id = 1234
- get_items:
handler: project/items/get.handler
events:
- http:
path: items/{itemId}
method: get
So far in the get.handler
I check event.pathParameters? event.pathParameters.itemId : null
if the specific item exists and call some getItem(itemdId)
function and if it does not exits I call a getAll()
function.
If I pass the item id in the path it works, but when I make a request for api.example.com/items/
I get the following error:
not a valid key=value pair (missing equal-sign) in Authorization header
. This means something is wrong in my path and I have to pass the item id to the path parameters.
My question is: Is there a way I can use multiple paths in the - http:
area, or what would be a recommended way to solve this issue (just create two separate handlers) ?
You can define more than one path resource, but by default, Serverless will generate them from the root resource. restApiRootResourceIdis optional if a path resource isn't required for the root (/).
Here's an example: # serverless.ymlfunctions:index:handler:handler.helloevents:-http:GEThello
The package section is what tells serverless to locate the artifacts. Let’s add another function to the auto-generated Handler class, which already has one function defined called handleRequest which maps to the lambda function hello, as noticed in the serverless.yml above.
As you can notice, the two functions can be invoked using their function names, while residing in the same Handler class. This is pretty useful when creating CRUD operations on resources without having to create a Handler class for each method. Found this useful? Let me know in the comments below!
There are two ways to easily accomplish what you're looking for.
Firstly, a lambda function can be triggered by multiple events. You can add another http
event to the array of handlers like so:
get_items:
handler: project/items/get.handler
events:
- http:
path: items/{itemId}
method: get
- http:
path: items/
method: get
Alternatively, you could use the {proxy+}
argument. You can read more about the various proxy methods here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With