In a previous blog post, we have created an API Gateway with a Lambda blueprint. With it, both the API Gateway and the Lambda function were automatically created and linked together. Now we will do this manually and see how an API Gateway can trigger a Lambda function.
Creating the Lambda function
First, we create a Lambda function as in the previous post but instead of selecting Use a blueprint we now select Author from scratch. We give our function a name. Under Permissions we won’t create a new role for this function, we will select our existing role that has been created by our blueprint.
After clicking Create function our Lambda code is created and is ready to be linked with our API Gateway. For this, we go into the API Gateway service.
We would like to use this function as a new resource so we create a new resource and in that a new method. On the method settings, we select our new Lambda function as we did before. We now can see in our API flow diagram how our newly created Lambda function is executed.
Upon clicking on Test we can test our new API call and everything looks okay. Are we sure?! 🤔
Is everything okay?
Remember, that we selected to use an existing role for our new Lambda function. Does our role have all the required permissions?
If we go back to Lambda and check out the Monitor section we see no errors.
But upon clicking View logs in CloudWatch we get an error.
This means that logging doesn’t currently work on our new Lambda function. We have to manually create a log group and allow our role to write to this log.
In the CloudWatch console, we select Log groups and click on Create log group and name our log group exactly as in the error message. In our case: /aws/lambda/simple-api-auth
💡 When the log group is created remember to note down its ARN because we will later need it.
Now, to allow our role to write to this log group, we have to go to IAM and modify our role. We see that the CloudWatch permissions are in the AWSLambdaBasicExecutionRole policy.
We now select this policy and click on Edit policy. Under the resources section, we click on Add ARN and add our newly created log groups ARN. Save the policy.
And we are done! We have added a new function to our API Gateway and set up the necessary permissions. 🎉
Takeaways:
- Keep your permissions maintained in IAM. Specify resources and only allow policies that are required.