8

As of Rails 5, API gem is in merged in.

Now, what does that leave us with in case I have API to call via AJAX from the webpage? I'm looking for a best practice here. Surely, I can make a route with JSON serializer myself. Then, there is a possibility to entirely separate API calls into another app.

Since API functionality is called by inheritance class ApplicationController < ActionController::API I can't really see an option to combine the it with standard ApplicationController < ActionController call.

Am I right? Would overloading on per-controller basis work?

1 Answers1

13

If you use the --api mode I think that you are right - you could not combine those. And this is made by design - ActionController::API is a subclass of ActionController::Metal. The idea is to have ActionController::API very skinny and lightweight. But, by enabling the api mode you create a "contract" that your application will be just an API, and that is it.

But, you could always have a both, a normal and an API controller in the same application, if you are using a normal Rails app. Then, the ActionController::API class will be available as well, so you can have an API namespace containing only the lightweight API controllers, and the rest in the global namespace.

For example:

class UsersController < ApplicationController
  * some code here *
end

and:

class API::V1::UsersController < ApplicationController::API
  * some code here *
end

Hope that helps!

Ilija Eftimov
  • 790
  • 8
  • 16
  • @BhushanLodha I haven't benchmarked this, but I doubt that the lack of a few abstraction layers will make a substantial difference in performance. I'd be glad to be proven wrong if someone has any data proving the opposite. – Ilija Eftimov Oct 26 '19 at 21:13