May 27, 2017   •   1 min read

How to Hide Your API Keys in Python

Protect your application’s API Keys while committing to Git.

If you plan on programming any applications and storing your code in a public GitHub repository then it is important that you protect your API keys 🔑 by ensuring that they are not searchable or otherwise publicly accessible.

What’s an API?

An application programming interface (API) is a structured set of instructions for building applications. If you want to leverage data from services such as Twitter, The New York Times, Slack, Spotify etc. then you should read their APIs to figure out how to structure your queries to receive data from their service or to post on their service.

What are API keys?

API keys allow developers to access APIs and are unique keys associated with that particular developer and/or application. Just like you shouldn’t share your passwords you should never share your API keys. It is important to protect your API keys so that people do not take any actions as you which could result in your API key being revoked due to somebody else exceeding rate limits or abusing/violating an APIs terms of service. A rate limit is when an application limits the number of API calls that a specific application or user can make during a specified period of time.

How do I protect my API keys on Github?

Here’s how to hide API keys in Python from GitHub using to store your sensitive API keys and tokens in a separate file from your main script. I used similar code when accessing the Twitter Search API for my blackgirlmagic twitter bot.

Create 3 Files in Your Application

This file will store your API keys. You just need to update the portion in the strings with your API keys, depending on the service you may or may not need all four types of API keys. These in particular are required to create a Twitter application.

This file will store your main script that needs to access the API keys. This file can be named whatever you like.


A .gitignore file tells GitHub to ignore the noted files, directories or files that end in specific extensions when committing files to GitHub.** This step is crucial to ensure that your file does not end up viewable on GitHub! Here’s a collection of useful .gitignore templates.**

Originally published at *Black Tech Diva.

Monica Powell   Twitter

Monica Powell is a web technologist that cares about increasing the visiblity of underestimated individuals in technology. In 2015, she received the #GIRLBOSS award from Sophia Amoruso’s Girl Boss Foundation. She’s currently focusing on making tech more enjoyable & accessible and is always up to chat data visualizations, web development or #BlackGirlMagic.

comments powered by Disqus