J

Sinatra inside of Rails

28 Jul 2013

I recently started building a new service in Ruby on Rails and had the need to build an API that users can interact with for their own applications or tools. Unfortunately, Ruby on Rails is a little bit heavy for this so I needed to find something that not only played nicely with my current setup but could also leverage the funcitonality I have already built.

I ended up settling on Sinatra. Why?

  • I would mainly be returning JSON, not full blown views.
  • Needed a clean and easy nested routing system - Rails can get very condeluded if not done correctly.
  • Routes are based around the HTTP verbs (GET, POST, PATCH, DELETE, etc) so it is intuitive to write routes and conditions.
  • You can use conditions on routes so the same endpoint can return different pieces of data based on user agent, host name, etc.

So I’ve decided on using Sinatra for my API, now, how to get it into Rails without blowing away my existing work? Thankfully, a few different repositories on GitHub had already done this but with pretty minimal documentation so here is the more documented version.

Add Sinatra to your Gemfile

To get Sinatra into your application you will need to add the following line to your Gemfile.

gem 'sinatra'

Don’t forget to run bundle install after updating to get the new gems installed.

Adding in the Sinatra endpoint

Now that Sinatra is available, let’s add the Sinatra file to our Rails lib directory inside of it’s own api directory so that we can keep all of the API files together. Inside of the api directory create a file called core.rb. This will be the base of our API.

$ mkdir lib/api
$ touch lib/api/core.rb

The directory structure should now look a little like this:

app
└── lib
    ├── api
    └── core.rb

# .. snip

Once you have created the core.rb file it is time to write the code that will enable your first response from the Sinatra application. Below is my endpoint that will render at http://localhost:3000/api.

module Api
  class Core < Sinatra::Base
   get '/api' do
     "Howdy, from your Sinatra API."
   end
  end
end

Autoloading for the lib directory

To ensure your Sinatra application is loaded on boot, you will need to add the following line to your application.rb.

config.autoload_paths += %W(#{config.root}/lib)

Routing to your application

Now that the lib directory is being autoloaded, you need to update routes.rb to tell Rails that the /api endpoint is going to your Sinatra applicaton.

match 'api' => Api::Core

And that’s it! You can now open your browser to http://localhost:3000/api and it should render your API response.