Your first Rails API

In six easy-to-code steps

Eric Nolte
4 min readJul 9, 2014

Step 1: Create a Rails-API application

Install the Rails-API gem and run rails-api new myapi. Load your gemfile with the gems “rack-cors” and “active_model_serializers”.

Run “bundle install” after you add your gems.

Step 2: Generate a model and controller for your data

Enter your app directory and generate your model:

Your model is just like any other Rails model. I chose guitars (nod @caike). Make sure to “rake db:migrate” as well.

Now for your controller:

You’ll probably want to provide basic CRUD methods but you don’t necessarily have to. My own first API serves only create and read.

Step 3: Set up your routes and application

Open up routes.rb in your config folder. The controller generator should have made GET routes for you. Replace those with:

I like my root page to route to the index route. That way I can easily see what, if any, data is being returned.

Step 4: Setup your controller

This is your most challenging step. In your controller, code in what JSON objects you want the API to return. For something small and simple I just return the entire collection and manipulate it client-side if necessary. Here is a very simple controller example:

Step 5: Open your API to Cross-Origin Requests

You’ll probably want to allow cross-origin requests so enter the following into your config/application.rb file:

Step 6: Fire it up

Run “rails s” to start up the server. If you set up your root to your read route you can now navigate to your browser to “localhost:3000" and see your empty JSON object. If you open your console on a site with jQuery loaded ( such as www.ericnolte.com) you can type in the following to post your first entry (do not try copy/paste, will not work through Medium!):

$.ajax({ url:”http://localhost:3000/guitars", data:”make=Gibson&model=Les+Paul&year=1986", type:”POST”, dataType:”JSON” }).success(function(json){ console.log(“POST successful”); });

A successful POST to your Rails database! You can now see the JSON object returned in the browser if you navigate back to localhost:3000:

And thats its! Your very own API to call :home. This is, of course, just a base and will need more work to be production-ready. If you’d like to view my own first API in action you can find it at www.ericnolte.com in the “Personal projects” section. Hope this helps you get started in building your own Rails APIs!

If you would like to further your Rails API knowledge I’d recommend these resources:

Screencasts by @joshvc and @greggpollackhttps://www.codeschool.com/

Github page for the Rails API gem — https://github.com/rails-api/rails-api

Github page for Rack-CORS gem — https://github.com/cyu/rack-cors

Railscasts on APIs by @rbateshttp://railscasts.com/?tag_id=37

And, of course, follow me on Twitter for my latest posts!

--

--