0

I've come across two scenarios with regards to creating a REST API in Rails and I wonder which one is preferred. Usually if you know that you're required to have a REST API for your application at start. Does it make sense to have it in a namespace and thereby duplicating the controller logic?

I've seen examples where people have an application already and later figure they need to extend and offer a REST API. The approach to this has been to create new routes with namespacein routes.rb and controllers/api/whatever.... This still yields duplicate code though, but might be more sensible approach. The difference being a stateless machine for the REST API calls.

Can anyone elaborate on the preferred approach, thanks.

H.Rabiee
  • 4,747
  • 3
  • 23
  • 35

1 Answers1

0

If you create a Rails application, and following the usual conventions, you basically end up with a REST API. Unless you are talking about a more specific meaning of the term (which I am not aware of), "REST API" is more a bunch of general characteristics of the API (i.e., things like statelessness, resource-based URIs if using HTTP, etc.).

So to turn the question right back to you: which case are you thinking about where a (conventional) Rails application is not by extension trivially a REST API?

AnoE
  • 8,048
  • 1
  • 21
  • 36
  • Well in the case of a normal application, you set the CSRF token in the BaseController, however this should be disabled if you wish to expose an API and operate on those actions, (again, not through the web application gui). How does one work around this and disable the CSRF yet enable it in 'normal' cases in the same Controller? – H.Rabiee Mar 16 '16 at 13:41
  • To disable CSRF, see http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html . You could use the `:with` option to raise an exception only if you are in a browser (non-API) environment. See http://stackoverflow.com/questions/10741339/do-csrf-attacks-apply-to-apis . – AnoE Mar 18 '16 at 12:42
  • thanks but I don't really know how to use that to solve my problem. – H.Rabiee Mar 23 '16 at 10:53