1

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!

Marco Sanfilippo
  • 293
  • 3
  • 19
  • Try this one: https://stackoverflow.com/questions/38000787/correct-way-to-implement-api-versioning-with-active-model-serializers/38001311#38001311 – Mirza Memic Sep 16 '16 at 18:23
  • @MirzaMemic thank you. I've read but now Serializer are not used by Rails. Please check update on question. – Marco Sanfilippo Sep 17 '16 at 13:53

2 Answers2

1

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.

Marco Sanfilippo
  • 293
  • 3
  • 19
Júlio Campos
  • 377
  • 2
  • 14
0

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.

Community
  • 1
  • 1
Marco Sanfilippo
  • 293
  • 3
  • 19