Reputation: 303
I need to namespacing API for a Rails based application.
I use Active Model Serializer
but now I need to versioning my API.
How?
I have yet subdomain constraints. For API, I wish to have...
api.domain.com/v1/users/
with (for example) :id
and :name
for User
api.domain.com/v2/users/
with (for example) :id
:name
:ranking
for User
So, how should I create different Serializer
, one for each namespace?
And... Must I create different Serializer
in different controllers or different files? How exactly?
Thanks to all.
UPDATE
Some code:
routes.rb
constraints subdomain: 'api', default: {format: 'json'} do #api.domain.com
#API V1
namespace :v1 do
#resources for v1
end
#API V1
namespace :v2 do
#resources for v2
end
I have in controllers/v1/resource_controller.rb
with module V1
and render json: @list
that renders ALL information of the resource.
So, Rails is not calling my serializer placed in serializers/v1/resource_serializer.rb
EDIT: Namespaces are valid!
Upvotes: 1
Views: 615
Reputation: 303
As suggested @Mirza Memic is better to specify also the serializer when call render json:
with each_serializer: TopModule::SubModule::CustomSerializer
otherwise we could get error (model_name
or read_attribute_for_serialization
) if is a collection (simply serializer:
instead of each_serializer:
ONLY if is a SINGLE object)
Of course controller must be "sub-foldered" for each module name, as suggested @Júlio Campos.
Upvotes: 0
Reputation: 407
You need to create 2 controllers, 2 serializers and define your routes.
namespace :api do
namespace :v1 do
resources :foo
end
namespace :v2 do
resources :foo
end
end
And your controllers:
class Api::V1::FooController < ApplicationController
#...
end
And
class Api::V2::FooController < ApplicationController
#...
end
Your serializers also need to have /v1 and /v2 in name.
Upvotes: 1