Wednesday, May 2, 2012

Twitter like Api routes for Rails 3

Twitter api routes follow the pattern 'http://api.twitter.com/1/statuses/mentions.format'.

The new Rails 3 routing makes it easy to implement this:

scope "/1", :constraints => { :subdomain => /^api(?:-dev)?$/, :format => :json }, :module => 'api/v1' do
  resources :projects, :only => [:index, :show]
  resources :tasks
end

which allows for routes such as

http://api.lvh.me:3000/1/projects
and
http://api-dev.lvh.me:3000/1/tasks

while neatly organizing your controllers under
app/controllers/api/v1/projects_controller.rb
app/controllers/api/v1/tasks_controller.rb

Note:
For rspec request specs, use the following pattern:


describe "/1/projects" do
  let(:url) { "/1/projects"}
  [:html, :xml].each do |fmt|
    it "rejects explict #{fmt} format" do
      get "#{url}.#{fmt}", nil, {'HTTP_HOST' => 'api.lvh.me'}
      last_response.status.should be(404)
    end
  end
end

njoy.

No comments: