I am currently in the process of designing a versioned API for a new website. I understand how to namespace the routes but I am stuck on the best way to implement versioned methods within a model.
The code samples below are using the rails framework but the principle of the matter should be consistent between most web frameworks.
The routes currently look something like:
MyApp::Application.routes.draw do
namespace :api do
namespace :v1 do
resources :products, :only => [:index, :show]
end
end
end
And the controller:
class Api::V1::ProductsController < V1Controller
respond_to :json, :xml
def index
respond_with @products = Product.scoped
end
def show
respond_with @product = Product.find(params[:id])
end
end
So obviously we're just exposing the attributes available on Product here, this solution works great if you're only going to have one version of the API. What happens when you want to release V2 and V2 needs to reimplement the way that Product's name is displayed (while maintaining backwards compatibility with V1 - at least in the short term)?
As far as I see it you have a couple of options...
name_2
- this seems equally dumbto[format]
on...Three and Four are the only ones that I can actually think makes any kind of sense... Three would look something like:
# model
class Api::V1::Product < Struct.new(:product)
def to_json
attributes.to_json
end
def to_xml
attributes.to_xml
end
private
def attributes
{:name => product.name} # add all the attributes you want to expose
end
end
# Controller
class Api::V1::ProductsController < V1Controller
respond_to :json, :xml
def show
respond_with @product = Api::V1::Product.new(Product.find(params[:id]))
end
end
What have other people done in the past?
Instead of one app serving V1 and V2 and V... you deploy one app for each version. One app is going to answer api.domain.com/v1, then another app is going to answer api.domain.com/v2 and so on.
That is how service oriented applications are best organised, each service should be isolated, an independent deployment.
Serving all versions from a single app defeats the purpose of service oriented design, since each time you make a change in one service you will need to test and deploy for all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With