DEV Community

kcarrel
kcarrel

Posted on

Major Key Alert: Hide your API Keys

I love integrating public APIs (Application Programming Interface) into my side projects in order to add in more functionality. However, this raises the issue of dealing with hiding API keys! This post will walk you through what an API key is used for, why you need to hide them and provide a guide of how to accomplish this in a Ruby project.

What is an API key?

An API key is a unique identifier used to control access to an API service provider. The API key links to the user who has been assigned the key and can be keeping track of amount of calls to the API being made by a user or which areas of the API the user is allowed to access.

Why do I need to hide my API keys?

Hiding your API keys is necessary because it is an identifier for your access to a resource. If you make that identifier publicly available someone else can use to it to represent themselves as you and abuse your access to the resource which could lead to your access being shutdown. Protect your access and your project by hiding those keys in a file that has been .gitignore(d) so that when you push your project up to it's github repository those API keys are not public and vulnerable.

Hide those keys! (Ruby)

  • Add gem 'dotenv-rails' to your Gemfile and bundle install

  • While in the root of your project's directory use the command '$ touch .env'

  • In that .env file create an variable (uppercase only) and assign it to your API key

#Inside the .env file

YELP_API_KEY=your_developer_api_key_from_yelp
  • Add your .env file to the .gitignore file
#Inside the .gitignore file

.env
  • You can access your API key throughout your ruby project like the example below
def yelp
   yelp = ENV["YELP_API_KEY"]
   yelp_url = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=#{category}&location=#{location}"
   res = HTTParty.get(yelp_url, :headers => {"Authorization" => "Bearer #{yelp}", "x-requested-with" => "XMLHttpRequest"})
    render plain: res.body.squish
end

Happy API Key Hiding!

Common Troubleshooting

Top comments (2)

Collapse
 
codestuff2 profile image
Adam Whitlock

Hiding sensitive info like api keys is definitely a good idea when you are pushing code up to github. I also use env variables.

I don't write ruby much, but I do write lots of PHP and Node.

For PHP you can implement this solution for doing .env files:
github.com/vlucas/phpdotenv

For Node I like to use dotenv:
github.com/motdotla/dotenv

Great article. Thanks for writing!

Collapse
 
clairemuller profile image
Claire Muller

What a clear explanation! Just what I needed :)