简体   繁体   English

如何在Rails应用程序和Rails API之间最佳共享路由

[英]How to best share routes between Rails app and Rails API

I am writing my first "real" Rails app after making a few successful learning projects and I'm still a little bit iffy on best practises for App vs API routes. 在完成一些成功的学习项目之后,我正在编写我的第一个“真实” Rails应用程序,但我仍然对应用程序与API路由的最佳做法有些怀疑。 Ideally, API routes will be RESTful, mainly revolving around using resources :articles or whatever, but I'm wondering which of the the following two scenarios is best 理想情况下,API路由将是RESTful的,主要围绕使用resources :articles或其他任何东西,但是我想知道以下两种情况中的哪一种是最佳的

  • Create the app itself using RESTful routes, then bolt on an API in the "api" namespace/subdomain for example, and after authentication, piggy back off the same routes (not sure exactly how to do the piggy backing yet with different authentication, but that will come later. Or; 例如,使用RESTful路由创建应用程序本身,然后在“ api”命名空间/子域中添加API,然后在身份验证后,piggy带走相同的路由(不确定如何使用不同的身份验证进行the带备份,但是那将在以后出现。
  • Create the app itself with whatever routes are semantic and work well (still ideally CRUD based), then create an entirely new set of controllers and routes for the API (RESTful) 使用语义上合适的路由创建应用程序本身,并且运行良好(理想情况下仍基于CRUD),然后为API(RESTful)创建一套全新的控制器和路由

I appreciate any feedback that anyone has. 我感谢任何人的任何反馈。

The default "Rails way" is to make your models available to different clients through a single set of URIs, handled by a single set of controllers — /articles for browsers, /articles.json or /articles.xml for programmatic access. 默认的“ Rails方式”是通过一组URI(由一组控制器处理)为不同的客户端提供模型,这些URI由一组控制器处理-用于浏览器的/ articles,用于编程访问的/articles.json或/articles.xml。 You can see that in Rails' emphasis on "resources", the respond_to mechanism in your controllers and so on. 您可以在Rails强调“资源”,控制器中的respond_to机制等中看到这一点。

This often works very well for simpler APIs that match the CRUD semantics closely. 对于与CRUD语义紧密匹配的简单API而言,这通常效果很好。 If yours for whatever reason does not, you might be better off with separating it out. 如果由于某种原因而没有,那么最好将其分离出来。

Try starting out the simple way by sticking to this 'one controller for both' approach. 尝试通过坚持这种“一个控制器兼备”的方法来开始简单的方法。 If you like, you could use 如果您愿意,可以使用

scope '(api)' do
  resources :articles
  resources :authors
  resources :comments
  # ...
end

to add an optional '/api/' path segment to your URLs - in this case, giving you both /api/articles and /articles , routed to the same controller. 在您的网址中添加可选的“ / api /”路径段-在这种情况下,将/api/articles/articles都路由到同一控制器。 This gives you an easy way out, should you later decide to switch to separate controllers for HTML and API access. 如果您以后决定切换到用于HTML和API访问的单独控制器,则这为您提供了简便的出路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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