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 (
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
Don’t forget to run
bundle install after updating to get the new gems
Adding in the Sinatra endpoint
Now that Sinatra is available, let’s add the Sinatra file to our Rails
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
This will be the base of our API.
The directory structure should now look a little like this:
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
Autoloading for the lib directory
To ensure your Sinatra application is loaded on boot, you will need to add the
following line to your
Routing to your application
Now that the
lib directory is being autoloaded, you need to update
to tell Rails that the
/api endpoint is going to your Sinatra applicaton.
And that’s it! You can now open your browser to
it should render your API response.