I am new to Rails and am trying to figure out where I put my API Token for the external API I am using (one of Google's). I have worked with APIs in the past with Sinatra, but the directory structure of Rails has thrown me off with where I need to place it so I can access it in the controller. After I place my token somewhere, I plan on creating a create method in the controller and parsing the json data there so I can access it in my corresponding view. If someone could help guide me in the right direction as to where I put the token so I can access it (best practices), and if I'm on the right track to use the token in a method in the controller so I can access it in a view.
I know this question might be generic but from what I have Googled, many people new to Rails might benefit from this as to where to put things.
2 Answers 2
You can add your API Tokens under config/initializers
. Although, you'll probably have a gem
or directions from corresponding API docs telling you what the best way is to implement them. But if you were implement them via an initializer, it would be something like this -
GoogleApi.config do |config|
config.client_id = "<Your Google API Client Id>"
config.client_secret = "<Your Application Secret>"
config.application_name = "<Your Application Name>"
end
And then you'll be able to use GoogleApi
in your controllers.
A good example is this guide from heroku
to access AWS
3 Comments
I would suggest loading your API keys via a rails initializer. The rails initializers exist in config/initializers and are plain ruby scripts that run after the servers starts up. Here you can do things like load configuration files etc. For example, config/initializers/google_oauth.rb could contain some plain ruby code to load up a config/.yml file holding your API credentials for non-production environments.
In non-production environments, you could load the API tokens from a yml file and in production you could utilize something like Figaro for Heroku or Dotenv for other environments (AWS, DigitalOcean, etc).
The important thing to ensure is that the local configuration file and your API token stay out of version control so as to avoid compromising your token and the security of your application.