Skip to content

Step13: Setting Up a Versioned RESTful API

Lev Brie edited this page Aug 1, 2013 · 8 revisions

For more information about setting up versioned APIs, see the awesome Railscasts on REST API versioning and OAuth with Doorkeeper. Also check out the Doorkeeper gem, which we'll be using here.

  1. Add in a namespaced API route to config/routes/rb:

namespace :api, defaults: {format: 'json'} do # pass in version # through scope so it can be included in an Accept Header # and not the URL scope module: :v1 do resources :posts end end ```

  1. Add an app/controller/api/v1/posts_controller.rb that responds to index and create actions:

module Api module V1 class PostsController < ApplicationController respond_to :json

  def index
    respond_with Post.all
  end

  def create
    respond_with Post.create(params[:post])
  end
end

end end ```

  1. We use Doorkeeper to lock down our API, so we need to add config.active_record.whitelist_attributes = false to the /config/application.rb file to avoid conflicts with ActiveRecord.

  2. Add gem 'doorkeeper', :git => 'https://github.com/applicake/doorkeeper.git' to your Gemfile if it isn't there already and run $ bundle install (we need the latest version since Doorkeeper has not yet released a stable version that's compatible with Rails 4).

  3. $ zeus g doorkeeper:install

  4. $ zeus g doorkeeper:migration (assuming you're using ActiveRecord, otherwise see the docs

  5. $ rake db:migrate

  6. $ rake db:migrate RAILS_ENV=test

  7. Add current_user || warden.authenticate!(:scope => :user) inside of the resource_owner_authenticator block in config/initializers/doorkeeper.rb and comment out the line raise "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}". Restart the application (if your using zeus make sure to restart zeus, then the server, then guard - $ zeus start, $ zeus s, $ guard, all in separate windows).

  8. Visit http://localhost:3000/oauth/applications and click on New Application to create a new OAuth Client Application. I've called my client application AngularApp and given a redirect uri of http://localhost:3001/auth/rangular/callback. This should generate a callback url, application id, and secret, along with a link to authorization code. The next step is to test our OAuth implementation by creating a simple OAuth client.