I have an application in Ruby on Rails with mvc framework. As of now, I have API calls in the controller but don't think this is the right place for them. What kind of file should all my API calls go in? Thanks
def getDetails(id)
api_response = HTTParty.get(base_uri, :query => {:DID => id, :DeveloperKey => devKey})
@json_hash = api_response.parsed_response
return @json_hash
end
If the API is going to be called from Model code, I would put the API code under the models folder. If it is going to be called from Controller code, then put the code under the controller folder. If you don't know, put it in the helpers folder.
As perfectly explained on Ruby on Rails guides, when people say they use Rails as an “API”, it means developers are using Rails to build a back-end that is shared between their web application and other native applications.
Like most of the other frameworks, Rails is also based on MVC pattern. It basically works as following: Requests first come to the controller, controller finds an appropriate view and interacts with model which in turn interacts with database and send response to controller.
API calls to external services (3rd party) are not specific to your app, as their service is available to everyone (in theory). It is my understanding that these sorts of features go in the lib/
directory because they are not app specific. Ideally you could then pull out the code from your lib
in your project, and drop it into someone else's lib/
in another project and it would still work just fine.
Put the call in the lib/
. If you want, you can create the a model from the returned data in your controller.
It would look something like this:
app/controller/
class YourController < ApplicationController
def getDetails
# keep in mind, api call may fail so you may want surround this with a begin/rescue
api_response = YourApiCall.new.get_details(params[:id])
# perhaps create a model
@model = SomeModel.new(fname: api_response[:first_name], lname: api_response[:last_name])
# etc...
end
end
lib/
require 'HTTParty'
Class YourApiCall
def get_details(id)
HTTParty.get(base_uri, :query => {:DID => id, :DeveloperKey => devKey})
@json_hash = api_response.parsed_response
return @json_hash
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With