Reputation: 2489
I have Rails application, I want the CRUD functionality in my android mobile.
Rails provides default respond_to actions (html, json, xml..etc) in all controllers. I have been developing mobile application for android. I want to do CRUD operation in my mobile Rails application. Can we use this default respond_to for API calls?
If we do separate namespace for API, same method / code written in default all controllers, have to write again for API all controllers also.
I can't able to apply RAILS DRY concept here!.
What are the best ways to do API functionality in Rails without repeating controller code or model code?
Upvotes: 1
Views: 288
Reputation: 26061
It can be done as stated a above. But I would not suggest it as seems to be the consensus. I would go head and create a separate base controller where you could do things like disable disable csrf checking. Also you would probably have a lot of token code being used in browser clients where you only need it in the api calls. Grape is a great gem build for this purpose.
Upvotes: 1
Reputation: 1607
Yes you can use default respond_to
method for api calls.
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
Another way is to specify default format in routes.rb
resources :clients, defaults: {format: :json}
These are DRY ways to make an API. To serialized json
properly you can use ActiveModel::Serializer or jBuilder Gem.
Rails has a special gem rails-api
specifically for creating apis. Consider using that instead of rails
Upvotes: 0