views:

692

answers:

1

What are the best practices for this? Rails comes with RESTful resources out of the box, but do you use those for your actual public API? If so, how would you accomplish versioning of your API (i.e. example.com/api/v2/foo/bar, etc)?

+4  A: 

Typically, APIs for my applications are indeed built on the same resources that make up the HTML interface. For some (not me), that might be just using the code that comes out of the scaffold generator—but regardless of whether I write it custom or let the generator handle it, there are very few instances where I expose resources only to the programmatic API and not to the end user view.

Versioning hasn't been a problem for the applications I've built so far, but I can think of two ways to implement it.

1) You could add routes with the prefix 'v1,' 'v2,' etc., that set a parameter that you can then access in the controller to specify the processing to occur:

in routes.rb:

map.resources :posts, :path_prefix => '/:version'

in posts_controller.rb

class PostsController < ApplicationController
  def index
    respond_to do |format|
      format.xml do
        if params[:version] == 'v1'
          # ...
        else
          # ...
        end
      end
    end
  end
end

2) You might also consider adding a custom response format for each version

in initializers/mime_types.rb

Mime::Type.register_alias "application/xml", :v1
Mime::Type.register_alias "application/xml", :v2

in posts_controller.rb

class PostsController < ApplicationController
  def index
    respond_to do |format|
      format.v1 do
        # ...
      end
      format.v2 do
        # ...
      end
    end
  end
end

The former would give you URLs like example.com/v1/posts.xml and example.com/v2/posts.xml; the latter would give you URLs like example.com/posts.v1 and example.com/posts.v2

Ben Scofield
Another option for versioning if the the actual business logic is different would be to use namespaced routes.
Kris