Can we use Rails default controller for Mobile API request?

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?


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.


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

链接地址: http://www.djcxy.com/p/45648.html

上一篇: 哪种方法适用于RESTful API请求?

下一篇: 我们可以使用Rails的默认控制器的移动API请求?