Execute a Ruby Method on Lambda With Api Gateway
Amazon now offers Ruby 2.5 Lambda functions! I was able to take advantage of this at my job. Lambda functions are great when you want to periodically run a script or do some stateless work. In the past, I have created Node and Python functions to pull data, send emails and push data to external API’s. In this post, I explore how I use the Ruby implementation of Lambda in order to verify if a URL is valid.
Writting this function is Lambda has many advantages that include:
- Not having to bear the cost of maintaining software
- Lambda is super cheap in my use case
What is Needed?
Create Lambda and Connect API Gateway
- Create a Ruby 2.5 Lambda function
- Under “Add triggers”, click “API Gateway”
- Choose API -> Create a new API
- Choose Security -> Open
- Click “Add” button
Test Basic Setup
def lambda_handler(event:, context:)
{ statusCode: 200, body: JSON.generate("Hello!") }
end
You should be able to visit the URL provided by the API Gateway and view the text “Hello”.
Lambda Parameter Consumption
- Go to the API Gateway service
- Go to the gateway hooked up to the lambda function
- Under “Actions”, click “Create Method”
- Click on “GET”
- Under “Integration Request”, click “Lambda Function”
- Click to reveal “Mapping Templates”
- Click “When there are no templates defined (recommended)” radio
- Add mapping template and set value to “application/json”
- Generate template “Method Request passthrough”
- Click “Save” button
- Now, all the request data will be forwarded to the Lambda function
- This means, we can pass a url param in the on the API Gateway which is consumed in the Lambda function
The final Lambda function is:
def lambda_handler(event:, context:)
url = event.dig('params', 'querystring', 'url')
valid = UrlValidator.valid?(url)
{ statusCode: 200, body: JSON.generate({valid: valid}) }
end
Debugging
In order to get the function working, I relied on the method test functionality provided by the API Gateway. On one tab, I had the Lambda code open. While in another tab, I had the client test.
You can find the test functionality by clicking the “GET” route, then clicking
In order to the the url
param:
- On the {urlValidator} text input enter, “url=whatever”
- Click the test button and see the results of running the Lambda function!