Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I used both techniques: writing API logic in the same controllers and making separate controllers for the API request.</p> <p>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.</p> <p>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).</p> <p>Another solution is to make controllers with a prefix. Ex: <code>ApiUsersController</code>. This would make your <code>routes.rb</code> file look ugly because you would have to manually specify the route to match the corresponding controller method.</p> <p>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:</p> <pre><code>GET /api/v1/users.json POST /api/v1/users.json </code></pre> <p>And then, in the future you can create another API version, let's say <code>v2</code>, without breaking existing applications that use the older version of the API.</p> <p>You can find more about namespaces here: <a href="http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing" rel="noreferrer">http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing</a></p> <p>An awesome tutorial about REST-full API with versioning: <a href="http://railscasts.com/episodes/350-rest-api-versioning?view=asciicast" rel="noreferrer">http://railscasts.com/episodes/350-rest-api-versioning?view=asciicast</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload