How to hide API key in Ruby
When I was building my very first Command Line Interface(CLI) app, I needed to use an API to get data. Not all API sites require you to have a key or token; however, these sites are usually providing you with limited data.
The very first thing you want to do is to get dotenv gem in your gem file.
gem 'dotenv', '~> 2.1', '>= 2.1.1'
or if you wish not to include a specific version of dotenv , you can.
then install the gem using
gem install dotenv -v 2.1.1
After installing your gem, make sure you require this gem on your environment file by typing the following :
require 'dotenv'
Dotenv.load
Once you get these two, you need to create a .env
file in the root of your directory.
After creating your .env, you need to store your token or API key in the .env file as a CONSTANT and export it as follows:
export TOKEN = paste your token here.
The most important part is to add your .env
in your .gitignore
.
After that, using ENV["TOKEN"]
notation, you can refer to your TOKEN without exposing it.
Next, pass your token variable to your URL to parse or any way you like to use it.
token = ENV["TOKEN"]"https://trefle.io/api/v1/plants?token=#{token}"
The references:
Dotenv. (n.d.). Retrieved February 24, 2021, from https://www.rubydoc.info/gems/dotenv/2.1.1