1

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?

Kannan S
  • 2,459
  • 1
  • 17
  • 17
  • Can't you write the code at one place only, and then use `format.html` for browser request, and `format.json` for API calls? – Arslan Ali Jun 16 '15 at 13:03

2 Answers2

1

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.

Community
  • 1
  • 1
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
0

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

Zain Zafar
  • 1,607
  • 4
  • 14
  • 23