I have a rails site which is mainly REST based and I want to add JSON API support.
For a clean code base, should I add this support within the existing controllers or create new controllers which only handle this API methods and then move all the common code to models/helpers?
I used both techniques: writing API logic in the same controllers and making separate controllers for the API request.
If it’s only an API, a small app used only by you, go with the default controller-model relation that rails offers. The code will be quite clean. Your routes file will be also clean.
If you have a website and you want to build an API along, do it separately. I’ve build one alongside the existing controllers and the code was too messy. I refactored the code several times, but I still didn’t like it (it’s also a matter of personal taste).
Another solution is to make controllers with a prefix. Ex:
ApiUsersController. This would make yourroutes.rbfile look ugly because you would have to manually specify the route to match the corresponding controller method.The working solution for me was to move all the API logic in separate controllers under an API namespace. Namespaces also let you do API versioning. So, for example, your routes will be:
And then, in the future you can create another API version, let’s say
v2, without breaking existing applications that use the older version of the API.You can find more about namespaces here: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
An awesome tutorial about REST-full API with versioning: http://railscasts.com/episodes/350-rest-api-versioning?view=asciicast