简体   繁体   中英

Structure my application for web interface and API

I have a web application that also provides an API. The API is fairly simple, so I am just handling it in the respond_to block and returning json if requested. Now I want to version my API. I was looking at versionist gem. This mentions using the api_version method in your config/routes.rb to change routes based on API version. I don't understand this though, since I would think the routes would be the same, but the behavior of the response would change.

My question is, do I need separate controllers for my web and API portions? Also, do I need a separate namespace for the API? Or is there a way to keep things as they are now?

There are some things you'd want to do differently when providing an API. One of them is the ability to set an API version so that you can enhance your API by adding a new version without breaking existing clients. If your API is extremely simple you can achieve this by providing a second set of routes that will include the version. You may use versionist for that. However, when you'll need to add versions, the simplest solution (and the one that keeps concerns well separated) will be to hold a separate set of controllers, and keep them thin so there is no code duplication. This may allow you to use additional gems for the API (eg RABL, JBuilder or rocketpants). There are railscasts on each of them, I recommend watching them to get some background on API building.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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