Creating a Rails API


We'll be using rbenv which is a powerful Ruby version Manager.

# Install rbenv
brew install rbenv ruby-build

# Bootstrap rbenv
echo 'export PATH=$HOME/.rbenv/bin:$PATH' > ~/.bash_profile  
echo 'eval "$(rbenv init -)"' > ~/.bash_profile

# Install latest version of Ruby
latestruby=$(rbenv install -l | grep -v - | tail -1 | xargs)  
rbenv install $latestruby  
rbenv global $latestruby

# Install Rails
gem install rails  


I ran into an error when trying to gem install rails. The reported error was with nokogiri and it read:

extconf failed, exit code 1  

Just run the following then try gem install rails again:

brew install libxml2  
gem install nokogiri -- --use-system-libraries --with-xml2-include=/usr/local/opt/libxml2/include/libxml2  

Initialize the API

The latest Rails has a api specific option. If you don't use the --api flag than Rails will scaffold out all extra cruft for generating views and such. We just want a headless Rails API so that we can serve the same data to a mobile app just as easily as to our website.

rails new my_api --api  

Generate a Model

rails generate model NAME [field[:type][:index] field[:type][:index]] [options]  

Generate a Controller

rails generate controller NAME [action action] [options]  

Run Your API

rails server