Josh R. answered 01/19/21
Full-Stack Ruby Developer
Making requests to 3rd party services is pretty straightforward inside the Rails framework. Technically speaking, you don't really use Rails to make these requests. Rails is more of a library/framework for building MVC style applications. But, you can do what you are asking! I like to use a library called RestClient. Here is an example for use inside of a Rails project.
The first thing to do is add RestClient to your Gemfile.
Afterward don't forget to bundle install. Once your bundle is up to date, you can use RestClient to make a GET request like this.
The response object that is returned, which is literally of class RestClient::Response, has a method on it called body. This is the one you use to access your data.
Is it a correct approach to use in my controllers?
Controllers are used as, a sort of middleman between your Views and Models. What this means is, controllers are taking requests made to your application and determining what data is needed ( interactions with Models ) and how to display that data to the requester ( using Views to do this ). So if you're using RestClient requests to obtain information that you will then use to augment data to be displayed, then you could argue that you should place that RestClient call inside a model or service object that your model then uses.
If your RestClient call is not used to augment data, for example you allow users to authenticate with Google or Facebook or you're using reCAPTCHA, you could place those calls inside one of your controllers. Ultimately, the decision is yours. You've got to make the decision that works best for the application you're building.
My opinion? I normally place simple web requests that need to be shared across multiple controllers inside a BaseController, that sits between my ApplicationController and however other many controllers that need that functionality. An example of this might be a simple geocoding request, where I just need the Lat/Lng. I define "simple web requests" as requests that require little to no processing of the result. Anything more complex I place in a service object so that I can contain specific business logic to one place.
Hope this helps!