Serverless Ruby on AWS Lambda with the Jets framework
Tags: ruby, serverless, rails, twilio
Published: 2019-05-23 01:17:11

---
title: Serverless Ruby on AWS Lambda with the Jets framework
published: true
tags: ruby, serverless, rails, twilio
canonical_url: https://www.twilio.com/blog/serverless-ruby-on-aws-lambda-with-the-jets-framework
cover_image: https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/oMX1dI2w2BskhPm3NagdjbXVb0t9ONMEUOR_7ms5C51r_d.width-808.png
---

When AWS launched [Lambda](https://aws.amazon.com/lambda/) in 2014 there was no love for Ruby. Platforms like Python, Node.js, and Java started the [serverless](https://www.twilio.com/docs/glossary/what-is-serverless-architecture) revolution for hosting and running functions in the cloud. At the end of 2018, support for Ruby was finally launched.

You can build with Ruby on Lambda using raw functions and [Serverless Application Model (SAM) templates](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) as described in [the getting started guide for Ruby on Lambda](https://aws.amazon.com/blogs/compute/announcing-ruby-support-for-aws-lambda/), but Ruby is all about developer happiness and when the config file is longer than your program the process could be described as painful. Enter the [Jets framework](http://rubyonjets.com/) a framework that "leverages the power of Ruby to make serverless joyful for everyone."

![The Jets Logo](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/MbSU26tM8FMRwHQ6hwnjPgtiseMlWDonId63c_uWs-eNUd.width-500.png)

## From Rails to Jets

Jets combines the experience of building a [Rails application](https://rubyonrails.org/) with the ability to deploy to AWS Lambda and related services, including [API Gateway](https://aws.amazon.com/api-gateway/), [S3](https://aws.amazon.com/s3/), and [DynamoDB](https://aws.amazon.com/dynamodb/). In this post we're going to see how to get started with Jets and deploy a Lambda powered Twilio application written in Ruby.

## What we're building

To keep things simple we're going to build an SMS based app and to make it a bit more fun, we're going to include a little humour. When you text into the application it will respond with a bad joke. Sorry, misspelling there, I meant a _dad_ joke, courtesy of the [icanhazdadjoke](https://icanhazdadjoke.com/) API.

This application will show us how to get started with Jets, create controllers, actions and routes. We'll build a single endpoint that responds to HTTP requests from Twilio when a number receives an incoming SMS message. The endpoint will return [TwiML](https://www.twilio.com/docs/sms/twiml) with a random dad joke each time and hilarity will ensue.

## What you'll need

To follow along with this project you'll need:

- A Twilio account ([sign up for a free one here](https://www.twilio.com/try-twilio))
- [An AWS account](https://aws.amazon.com/)
- [Ruby 2.5](https://www.ruby-lang.org/en/downloads/) (the version supported by Lambda) and [Bundler](https://bundler.io/) installed. If you don't have Ruby 2.5 installed, you can use one of [the tools listed here to install and manage your Ruby versions](https://www.ruby-lang.org/en/documentation/installation/#installers).

Got all that? Then let's get started.

## Getting started

We'll start by installing the `jets` gem globally. On the command line type:

```bash
gem install jets
```

The Jets executable can then be used like Rails as a generator to initiate a new project and then run commands within the project. We'll create a new project now, but given our scope in this post we are going to limit it a little. First up, we're going to create the project in API mode as there's no need for HTML views in this application. That also avoids asset compilation with [webpacker](https://github.com/rails/webpacker), which will save in our build time. We also don't need a database. Run the following command to create a new project:

```bash
jets new dad-jokes-sms --mode api --no-database
```

Once the generator has finished running, change into the `dad-jokes-sms` directory and run your application locally with the following command:

```bash
jets serve
```

Open up [http://localhost:8888](http://localhost:8888) and you will see a page that look like this:

![The Jets welcome page open in a browser.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/5Ux-cijdn83L7eiOHmlJvLy2XYQ-j7cFTijkQTuKrFzTRE.width-500.png)

If you see this page then your new Jets project is running successfully.

## Our first Jets controller

Now we have a Jets application we can use the gem to generate parts of our application, from models and controllers to full scaffolds. For our application we're going to need a controller with one action. Generate it with the following:

```bash
jets generate controller Messages create
```

The generator will create and edit a number of files for us. We need to check the new routes so open `config/routes.rb`.

Jets generated a `GET` route, but Twilio webhooks make `POST` requests by default and I prefer to keep it that way.  Set the application up to receive `POST` request webhooks on the `/messages` endpoint instead like so:

```ruby
Jets.application.routes.draw do
  post 'messages', to: 'messages#create'
  root "jets/public#show"

  # The jets/public#show controller can serve static utf8 content out of the public folder.
  # Note, as part of the deploy process Jets uploads files in the public folder to s3
  # and serves them out of s3 directly. S3 is well suited to serve static assets.
  # More info here: http://rubyonjets.com/docs/assets-serving/
  any "*catchall", to: "jets/public#show"
end
```

Now, let's go write our controller action. Open `app/controllers/messages_controller.rb` and you will see one method for the `create` action. This is the action which will receive our Twilio webhook and respond with TwiML to send back a dad joke.

### Fetching a dad joke

To send back a dad joke we need to make a call to the [icanhazdadjoke API](https://icanhazdadjoke.com/api). Let's write a quick private method we can use to achieve this.

We'll use `open-uri` as it's useful for making simple web requests (including [downloading files and images](https://dev.to/twilio/how-to-download-image-files-in-ruby-4f2a)). The API will respond with plain text if we ask it to, which saves us doing any parsing. Add the following to the `MessagesController`:

```ruby
require 'open-uri'

class MessagesController < ApplicationController
  def create
  end

  private

  def random_joke
    open('https://icanhazdadjoke.com/', { 'Accept' => 'text/plain' }).read
  end
end
```

Now we're ready to return our joke to Twilio as TwiML.

### Returning TwiML

We'll build up a response using the helpers from the twilio-ruby helper library. Open the `Gemfile` and add `twilio-ruby`:

```ruby
source "https://rubygems.org"

gem "jets"
gem "twilio-ruby"
```

On the command line, run `bundle install` to install the gem. Now in the `create` action instantiate a new TwiML response object, reply to the incoming message using the [`<Message>` TwiML element](https://www.twilio.com/docs/sms/twiml/message) and render the XML response, like so:

```ruby
require 'open-uri'

class MessagesController < ApplicationController
  def create
    twiml = Twilio::TwiML::MessagingResponse.new
    twiml.message body: random_joke
    render xml: twiml.to_xml
  end

  private

  def random_joke
    open('https://icanhazdadjoke.com/', { 'Accept' => 'text/plain' }).read
  end
end
```

You can [read more about how to use the `twilio-ruby` helper library for generating TwiML](https://www.twilio.com/docs/sms/twiml/message) in the documentation.

We can run this locally to test we are getting the expected response. If you stopped the application, start it again with `jets serve`. Make a `POST` request to localhost:8888/messages using `curl` and you'll see your joke, provided by [icanhazdadjoke](https://icanhazdadjoke.com/), in the TwiML response:

```bash
curl --data "" http://localhost:8888/messages
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>What’s the advantage of living in Switzerland? Well, the flag is a big plus.</Message>
</Response>
```

Great, our Jets application is working! Now to deploy it to AWS Lambda.

## Are you ready to deploy? IAM!

To deploy our Jets application to AWS we first need to set up our project with credentials to allow it to access AWS services. A good practice here is to create a user that has the minimum number of permissions required to do everything it needs to. The [Jets documentation describes the minimum permissions](http://rubyonjets.com/docs/extras/minimal-deploy-iam/) that our user will need. Within our AWS account we're going to create a policy that contains these permissions and a new user that will be assigned the policy. We can then use that user's credentials to deploy our application.

In your [AWS console](https://console.aws.amazon.com/console/home) find the _IAM_ service (or head straight to the _IAM_[ section](https://console.aws.amazon.com/iam/home)).

![Select IAM from the AWS dashboard](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/8v8dtoFQGT1xLEbege9lrVmCpy6wsbH8zOeEeYt0bC2lFH.width-500.png)

Go to the _Policies_ section and create a new policy.

![Navigate to policies and create a new policy.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/h_Hjb1Mr3f4b9wdpQ29dIvqiWx2sMhtClfqCs841tHQtLU.width-500.png)

Choose the JSON tab and enter the following JSON [from the Jets documentation](http://rubyonjets.com/docs/extras/minimal-deploy-iam/#commands-summary):

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "apigateway:*",
                "cloudformation:*",
                "dynamodb:*",
                "events:*",
                "iam:*",
                "lambda:*",
                "logs:*",
                "route53:*",
                "s3:*"
             ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

Click through to review the policy and give it a name.

![Give the policy a name on the review page then save.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/4jwzDK_cmz_1Et8KGGeiaBNxVVHs9QJwzP9xumd4tTgfHW.width-500.png)

Save the policy. Now we need to create a new user and attach the policy to it, giving it the permissions to create the resources Jets needs to deploy. Open the _Users_ section in the _IAM_ console and create a new user.

![Navigate to Users and create a new user.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/3dt4UQR8aYoKlckCHlw113K3jxhHCGMRJ2rhPDGI1peBow.width-500.png)

Give the user a name and select _Programmatic Access_ for the _Access Type_.

![Name the user and check the check box for programmatic access](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/usEXv2bqNxbt3FPo0nJAkKEvm0YUTs62el40415Uu7e2ys.width-500.png)

Click _Next_ to choose the permissions for your new user. Choose _Attach existing policies directly_ and filter for the name of the policy you just created. Select that policy and click _Next_.

![Filter for the policy you just created and select it.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/JORcX2AMUcp2pITsVXjLbxXpPNsO_obGu2lhRYjEzC83X8.width-500.png)

Click _Next_ until you reach the success page.

![Success, you have created a new user.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/XNdTXkfWx0BCu-UDHI1HZZBI_TOLxJ0u4qh9rYQTmMyTGr.width-500.png)

Save the _Access key ID_ and _Secret access key_ from the last screen. We'll need them to deploy with. Now we're ready to deploy.

## Deploying to Lambda

On the command line enter:

```bash
AWS_ACCESS_KEY_ID=YOUR_USER_KEY AWS_SECRET_ACCESS_KEY=YOUR_USER_SECRET_KEY jets deploy
```

Jets will use the credentials as environment variables to set up all the resources in your AWS account to run the application. It takes a little while, but when it is complete you will have a URL where your application is running.

![The last line of the output will include your application URL.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/D1fQn-0PRn7qXbHYvuIQT-vyo0jiar9lzG4BnVQ9ZY7wwx.width-500.png)

You'll notice this deployed to a "dev" environment. You can read more about [how Jets handles environments](http://rubyonjets.com/docs/env-files/) in the documentation.

We can now test this URL using `curl`. Remember we use the route `/messages` so add that to the end of your API Gateway endpoint and make a `POST` request.

```bash
$ curl --data "" https://YOUR_API_GATEWAY_ENDPOINT/messages
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>I knew a guy who collected candy canes, they were all in mint condition</Message>
</Response>
```

Now to have dad jokes on hand at all times let's hook this up to a Twilio number.

## Dad jokes by SMS

Head into your [Twilio console](https://www.twilio.com/console) to your [active phone numbers](https://www.twilio.com/console/phone-numbers/incoming). If you already have a number you want to work with, edit it, otherwise buy a new number that can receive incoming SMS messages. In the field for _A message comes in_ enter your application URL.

![Enter the URL in the field for when a message comes in.](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/4cnCTI_Ww8IL6cgeyp-zlAIVlx6V_hvvdrT1ocjHfFgsTL.width-500.png)

Save your number and send it a message. You should get a dad joke in response. Now, in celebration, go and tell someone nearby that joke and let me know whether they laugh or groan.

## Serverless Comedy

In this post we've seen how to get started with Jets to write Ruby applications that you can deploy to AWS Lambda. You can see the full [project on GitHub](https://github.com/philnash/dad-jokes-jets).

There's a lot more to what Jets can help you accomplish, including responding to [events](http://rubyonjets.com/docs/events/), [storing data in databases](http://rubyonjets.com/docs/database-support/) and even [run your existing Rails application](http://rubyonjets.com/docs/rails-support/). Check out [these articles from the Jets documentation for more on what you can do with Jets](http://rubyonjets.com/docs/articles/).

Are you excited about running Ruby in a serverless environment? What do you think of Jets? Let me know in the comments or drop me a message on Twitter at [@philnash](https://twitter.com/philnash). Feel free to share your favourite dad jokes with me too!