In the previous post, we added a lambda function and set up the endpoint to our serverless API to get words of the logged in user from the DynamoDB table.
In this part, we would add an endpoint to our API to get the word by its id.
Create a file named getById.ts
under src/modules/words
:👇
(here is the code gist)
Add the API Endpoint function in serverless.yml
Next, configure the API endpoint to map to the above function we added.
In serverless.yml
, add a getWord
function in the functions
block as shown below:👇
functions:
createWord:
...
...
...
getWord:
handler: src/modules/words/getById.main
events:
- http:
path: words/{id}
method: get
cors: true
authorizer: aws_iam
This is similar to the as the previous endpoint function createWord that we added in the previous section.
👆 We added a new function getWord
.events: — http, method:get
⇒ This means the event to trigger this function is http get
. path: words/{id}
⇒ The endpoint would have the path /words/{id}
, handler: src/modules/words/getById.main
⇒ the request would be handled at the main
function in the getById.ts
file (we added above).cors: true
⇒ to support CORS as the frontend would be on a different domain.authorier: aws_iam
⇒ this means the access to the API is restricted as per the IAM permissions of the federated identity that the user has been authorized with. We will see how exactly this would work when we would set up an Identity Pool from AWS Cognito service.
Add mock data to test the service locally
From your AWS Console →DynamoDB → tables →words-dev table → Items, note down the wordId
and userID
of the Item/record that we have posted to the table in the last part when testing the create-word API.
With this id, set the mock data, create a file named getbyId.json
under mocks/words
with below data:👇
With the mock data ready, let’s test our lambda function
$ serverless invoke local --function getWord --path mocks/words/getbyId.json --stage dev
Cool, our GET word API using wordId is working.
Deploy the service to AWS
$ npm run devDeploy
Great, now we have an endpoint to get word by its id. Next, let’s add the endpoint to update a word.
← Prev: GET words
┈ 🏠 ┈ Next: Update word
→