Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Damian Sieczkowski
Damian Sieczkowski
9,730 Points

JSON REST structure for rails app

Hi,

I'm building a iOS mobile application with a rails backend. At first when I started building the API I created a separate namespace for it and the controllers would respond with "render: json." Now, knowing a little more about routes I realize that I can set a respond_to and respond_with in the controllers thus eliminating the need for any separation. Assuming that at some point there will also be a web application along with other mobile clients is this the best approach? Will this offer more flexibility for programmers who may want to refactor the code later or vice versa?

1 Answer

Kyle Daugherty
Kyle Daugherty
16,441 Points

I would recommend sticking with the separate namespace. Take a look at this RailsCasts:

REST API versioning

Damian Sieczkowski
Damian Sieczkowski
9,730 Points

That's a great video - thanks! It addressed all of my questions. I kind of took out the namespace from my routes but I will put it back now & add a version as well. For anyone referring to this question... The only thing I did not notice in the video is that you can use capital letters for API when specifying the module in your controllers if you would like by adding this to config/initializers/inflections.rb -

ActiveSupport::Inflector.inflections(:en) do |inflect|
 inflect.acronym 'API'
end

and also have your path set to "/" instead of "/api/v#/" if you're using a subdomain already by adding the path option in your route ie -

  namespace :api, path: "/", defaults: { format: "json" }, constraints: { subdomain: "api" } do