DEV Community

Cover image for Building an API with Ruby and the Serverless Framework
We're Serverless! for Serverless Inc.

Posted on • Originally published at serverless.com

Building an API with Ruby and the Serverless Framework

Originally posted at Serverless on December 4th, 2018

On the heels of re:Invent, it’s been a great week for the serverless community. And one of the most exciting things in AWS’s re:Invent goodie basket? Ruby support for Lambda!

Personally, I love Ruby, and was really excited to play around with a Ruby deployment on the Serverless Framework.

So here you have it, Ruby fans. Your Ruby + Serverless Framework getting started template. I’m going to start by covering some Ruby + Serverless Framework basics and testing practices, and then we’ll build a fully-fledged Ruby API.

Let’s get to it.

Getting Started

First up, we need to install the Serverless Framework (if you haven’t already), and create a new Ruby service:


Navigate to your new service folder, and deploy the default hello world:

Testing Locally

Right now the framework only supports NodeJS, Python and Java in the local testing. (We hope to get that updated soon!) In the meantime, because Ruby is awesome, we have some great testing tools and capabilities right at our fingertips with some of the built-in testing tooling.

Let’s say we want to run our local handler and make sure it returns the status code:


Open test/handler_test.rb in a and copy/paste in the following code:

If we run ruby -I test test/handler_test.rb, we'll get a nice simulated invoke (assuming you have Ruby installed locally of course).

We’ll dive a bit more into this in the next more advanced section, building an API!

Building an API With Ruby, the Serverless Framework, and AWS Lambda

Building on what we already have in serverless.yml, let's add an event to our function:


Let’s also update our handler.rb with a some more interesting logic. We're going to echo back a posted request body as part of the message.

If we don’t get a request body or something else goes wrong, we handle that as well:


As always, let’s update our test to make sure we’re still happy. Make test/handler_test.rb contain the following:

After running a quick ruby -I test test/handler_test.rb to make sure all our tests still pass, then an sls deploy, we should have an API!

Grab that POST endpoint, run a curl against it, and you should see something like the following:

Ruby Examples

I can’t wait to see what the serverless community builds with Ruby! When you make your first (or fifth) Ruby app, please do submit it to our Examples Repo and share it with the community.

Here are some great community examples contributions we’ve already gotten: — aws-ruby-simple-http-endpoint

Originally published at https://www.serverless.com.

Top comments (0)