ruby-on-railsgrape-apigrape-entity

How to dynamically change formatter in grape API?


My API should some times return data as CSV format. But depending the data returned, the CSV formatter act differently (as hierachical data, should be flatten following specific rules depending the data) So i've written many customs CSV formatter. But I've discovered I can't change the formatter dynamically :

I'm using and want to use Grape::Entities, The API should be able to expose data as json, xml and csv.

I've tried :

desc 'My API 1'
get '/' do
  formatter :csv, CustomCsvFormatter
  present my_data, with: MyEntity 
end

But it fail since formatter isn't a defined method in this context.

I've tried :

desc 'My API 1'
formatter :csv, CustomCsvFormatter
get '/' do
  present my_data, with: MyEntity 
end

desc 'My API 2'
formatter :csv, CustomOtherCsvFormatter
get '/blublu' do
  present my_data, with: MyEntity 
end

But only CustomOtherCsvFormatter for all methods. The last formatter replace previous defined.

Did there is a way to change formatter dynamically ?

Did you see other way to do what I want ? : Output grape entities with a custom formatter depending the API method.


Solution

  • Using nested resources, make it work :

    resource :bidules do
      desc "My API 1"
      formatter :csv, CustomCsvFormatter
      get '/' do
        present my_data, with: MyEntity
      end
    
      resource :blublu do
        desc "My API 2"
        formatter :csv, CustomOtherCsvFormatter
        get '/' do
          present my_data, with: MyEntity
        end
      end
    
    end