Structure my application for web interface and API - ruby-on-rails

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 (e.g. RABL, JBuilder or rocketpants). There are railscasts on each of them, I recommend watching them to get some background on API building.

Related

Is it possible to consume the ActiveAdmin API endpoints alone with a custom UI and a frontend framework like Angular/React?

Just been researching about this approach and never seem to find a concrete answer online.
I'm seriously curious about the chances of only consuming the API for activeadmin. Then using the JSON objects in React or Angular with a custom UI.
Is this doable?
Absolutely! See https://blog.heroku.com/a-rock-solid-modern-web-stack
For notes on ActiveAdmin vs Rails Admin and other alternatives see https://github.com/activeadmin/activeadmin/wiki/Alternatives
I've also used both Grape and GraphQL in different places, one for performance, the other for flexibility, both reasonable choices.
In theory it is possible since you would just be using the endpoints provided but I think it would be far a far better design choice to choose another API framework gem like grape. One of my complaints with ActiveAdmin has always been that it is not very flexible and you can quickly run into limitations which means that you can't add features that you want to. IMHO you would be digging a pit instead of opening possibilities.
Personally I really like GraphQL (which would be another option) and the graphql-ruby gem is easy to set up and start making highly reusable components that can be leveraged from anywhere admin or frontend.

Rails REST API Practices

I've come across two scenarios with regards to creating a REST API in Rails and I wonder which one is preferred. Usually
if you know that you're required to have a REST API for your application at start. Does it make sense to have it in a namespace and thereby duplicating the controller logic?
I've seen examples where people have an application already and later figure they need to extend and offer a REST API. The approach to this has been to create new routes with namespacein routes.rb and controllers/api/whatever.... This still yields duplicate code though, but might be more sensible approach. The difference being a stateless machine for the REST API calls.
Can anyone elaborate on the preferred approach, thanks.
If you create a Rails application, and following the usual conventions, you basically end up with a REST API. Unless you are talking about a more specific meaning of the term (which I am not aware of), "REST API" is more a bunch of general characteristics of the API (i.e., things like statelessness, resource-based URIs if using HTTP, etc.).
So to turn the question right back to you: which case are you thinking about where a (conventional) Rails application is not by extension trivially a REST API?

What would be the best way to use AngularJS with Ruby on Rails?

I'm about to start a new project and I am unsure if using AngularJS for my front end would be a good idea not. I've read about people saying this isn't the smartest way of doing a project. And even if I did, Is there a way to get AngularJS to interact with the controllers? This question may be redundant but I am actually curious of how to effectively do this without it being a waste of time.
I've never completely done it, but I believe the way to go is to build a Rails api and then have a separate Angular project use said api. The api could also be used to build a mobile app. I think the Angular project would still need to be served from a Node.js server in production, but I don't think that would be a big deal.
This is what I used to learn how to build a Rails api: http://apionrails.icalialabs.com/book/chapter_one
You can do it within an existing project and share the models from it.
There are several different approaches to accomplish that. I tried about 5 different guides out there, the best I found (and I finally sticked to) was https://thinkster.io/angular-rails - This guide should help you build a basic CRUD app with angular connected to rails.
You use Rails as an JSON RESTful API which responds to Ajax-Requests (Get, Post, Put, Delete). Angular will handle the frontend stuff - sending those Ajax requests to the routes/methods defined in your rails controllers. So yes, of course your AngularJS app can interact with your rails controllers.
This also helped me to understand the setup in the beginning: Instead of the Rails View, you will be using AngularJS as your view:
I really love using angular with rails, because setting up the JSON responses (especially with Active Model Serializer Gem) is very easy and quickly done. i deffinitely can recommend it, and I have not encountered any unsolvable problems - so far.
Just go trough this guide I linked and you will see if this setup fits your needs.
The short answer is that your Rails application will have to present some kind of a public API for your AngularJS application to consume. Angular (and it's brethren, like React and Ember) runs client-side, on the browser, and it needs "something" to make AJAX calls against. That "something", i.e. your backend, can be Firebase, Parse, AWS Lambdas, Rails API, etc. Since you already have a Rails application, it probably makes the most sense to add some RESTful API endpoints that use the existing models (and possibly controllers) to consume/produce JSON payloads from/for the client.

How to manage multiple APIs in Rails

I have a Rails backend that serves multiple clients:
Angular JS App
iOS App
At first, I only had the iOS App, and used classical API versioning in rails when substantial changes were brought to the client (naming my versions v1, v2 and so on).
When we came up with the Angular front end, we needed a specific API, so I did a new version that I would use only with Angular (let's say v5).
At that point, v1 through v4 are dedicated to iOS, and v5 to Angular.
Obviously, I can simultaneously update my backend along with my Angular API, since both are served to the client every time they access the website. Therefore, there is no need for the Angular API to be versioned.
However, I'm at that point where I need to update my iOS API, and it is starting to get very wrong : v1..v4 are for iOS, and v5 is taken by Android. So the supposed next iOS API should be... v6? Definitely wrong.
I wanted to know if it was possible to name an API version angular, and thanks to this answer on SO I understand why this is not possible. I'll quote the interesting part for my case:
Ryan Bigg wrote:
I couldn't figure out how to get /api/asdf/users to match, because how do you determine if that is supposed to be a request to /api/<resource>/<identifier> or /api/<version>/<resource>?
Now you understand better my situation, here's the question.
The question
How am I supposed to manage multiple APIs, but which are not really like versions?
Is it possible to subdivide API versions? Like:
api/angular/v1
api/ios/v5 (moving v1..v4 to api/ios/ as well)
api/android/v1
Is there any best practice to do so? Or should I just be using the current API versioning system, knowing which version corresponds to which client?
I think in the end this is a design issue. Your API should be thought of as the methods to access your model in networked MVC. Just as in any MVC the model should be independent of it's view and controller. I think having a different API per client is almost like having a different model for each client, which I don't think is what you are intending.
As an example, (I am assuming your API is Restful), a GET request to
api/v1/user/1
might return a json "view" of user 1, each of your clients should be written to work with that same output. If you decide you will no longer support this, or add or remove some content from the returned json that would break an existing client, then you might bump the version and implement the change on that version
I would suggest your next API version expose all of the resources needed by any clients you currently have, and then overtime update your clients to work with this new unified API. If you find your self making changes to your model (API) that would break an existing client, then you can release a new version, allowing existing clients to continue to work with the old API and new or updated clients can pick up the new version.
A set of automated tests on your API will help identify when you break an existing client.
I am not expert at this, but I did (as a learning project) create a rails app with an api, and I was able to use the same api for android and ios.
In regards to your routing issue quoted from Ryan Bigg, you can resolve it by applying a constraint to the route. For example:
get /api/:type/:version/users/all, to: "users#index", constraints: {type: /(ios|angular)/, version: /\d+/}
Ensuring the the version is a number and the type is either "ios" or "angular", you can easily set up the routes for two separate APIs.
To answer the questions as to whether or not it is possible--yes. Anything is possible, especially with Ruby!
I, first of all, would not have two separate APIs to manage. However, if I did, I would create separate namespaces for each API and name the as AngularAPI and IosAPI. I would just route to them separately. The correct answer will depend on how exactly you've set up your API system.
How would I maintain two separate APIs? (from the comment)
It depends on how substantially different the APIs are. If there are only a few differences, it would make sense to simply use a different controller with different routes. For example, AngularUsersController and IosUsersController. They would both extend a ApiUsersController and alter only what was needed for each platform. This would still allow for proper versioning as it grew, and also keep code duplication at bay.

Understanding APIs

I was reading through the RABL git https://github.com/nesquena/rabl and I quickly came across this line. Can someone quickly explain what he means by "generating APIs"?
When using the ActiveRecord 'to_json' method, I tend to quickly find myself wanting a more expressive and powerful solution for generating APIs.
From my understanding an API is a set of classes / methods that may be used to interact with the content of the API creators material. With that definition, I believe he is saying that he wants to be able to interact easier with the API so he build RABL which allows for the content to be translated from his application to, in this case, Rails eaiser?
In this case, API is applied to the system as a whole. So your entire website might have an API that your customers would use to pull/send data to your system.
Mostly, these are JSON/XML endpoints that accept and return data. Rabl (and other serializers like it), help you craft custom JSON responses.

Resources