-
Notifications
You must be signed in to change notification settings - Fork 0
Step13: Setting Up a Versioned RESTful API
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.
-
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 ```
-
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 ```
-
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. -
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). -
$ zeus g doorkeeper:install
-
$ zeus g doorkeeper:migration
(assuming you're using ActiveRecord, otherwise see the docs -
$ rake db:migrate
-
$ rake db:migrate RAILS_ENV=test
-
Add
current_user || warden.authenticate!(:scope => :user)
inside of theresource_owner_authenticator
block in config/initializers/doorkeeper.rb and comment out the lineraise "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). -
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.