简体   繁体   中英

Should I use `respond_to` or have a dedicated API namespace in Rails?

In a Rails web app it's common to have some actions in your controller return JSON as opposed to an HTML view.

This is especially common if you are using many Javascript components that require JSON responses.

I was writing such an action the other day and wondered if I should move all my JSON responses to an API controller namespace. This is not to provide an API for a future fully front-end app, but rather just to separate JSON responses into their own namespace.

Is this good practice or overengineering?

In my experience it's good practice to separate UI and API controllers, for a couple of reasons:

  • The UI and API actions that one needs for a given model are never one to one. It's confusing to have a controller in which some actions respond to both UI and API requests and others only respond to one or the other.

  • UI and API responses need different support from the controller: different included modules, different helper methods, different filters and so on. It's much cleaner to have two different controllers for a given model, one with only the features it needs to support UI reponses and another with only the features it needs to support API responses.

In fact, using single controllers to serve both UI and API responses is a great example of how deduplication (of routes and actions) can make your code worse.

OOP

If you're only expecting JSON responses, I would keep to the controller you have, and employ the responders gem:

#app/controllers/your_controller.rb
class YourController < ApplicationController
  respond_to :html, :json

  def show
     @x = Y.find params[:id]
     respond_with @x
  end
end

Controllers are meant to deal with RESTful infrastructures. This means that they should be used to manipulate / invoke objects into the view. Not to be confused with the role of Models , controllers should combine / change objects depending on the action.

If you're trying to pull completely different data through your JS, then it may be worth creating an API to handle it all. However, you should refrain if you can just get away with a few simple adaptations in your "front-end" controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM