As we stated at the beginning of this chapter, every AWS resource is an entity and some services and our own accounts are actors. In this case, we have an entity, Lambda function, and an actor, API Gateway, which tries to invoke the Lambda function . On the other hand, we did not allow API Gateway to access our Lambda function; therefore, it cannot invoke it.
To solve this issue, we have to add an extra resource to our CloudFormation file, which is AWS::Lambda::Permission . Here is our snippet to be added to the end of the Resources section:
"TestLambdaPermission": { "Type": "AWS::Lambda::Permission", "Properties": { "Action": "lambda:InvokeFunction", "FunctionName": { "Ref": "TestLambda" }, "Principal": "apigateway.amazonaws.com", "SourceArn": { "Fn::Sub": "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${RestApi}/*" } } }
Here, we give lambda:InvokeFunction permission to the apigateway.amazonaws.com entity when the Source ARN matches the API we are creating in this stack.
After redeploying the stack, you can test the method again using the Test button, and you can see the result.