Store API Credentials For Open Source Projects

One issue which repeated comes up is how to manage private API credentials when the project is available on GitHub. This is the method I use for my own projects. I store all credentials in a JSON file and tell gitignore to not upload that file. Then when I am running that code locally, load the API credentials from the JSON file.


import json

Step 1: Create a JSON with the API credentials

credentials = {'access_secret': '392n39d93',
               'access_token': 'sdf424f',
               'consumer_key': 'sdf3223',
               'consumer_secret': 'dsf2344'}
with open('credentials.json', 'w') as f:
    json.dump(credentials, f, ensure_ascii=False)

Step 2: Add File To gitignore

Follow the instructions here.

Here is an example of a good gitignore file.

Step 3: Retrieve The Credentials From The JSON File

This step should be the one done inside your project or script.

Load JSON File

# Import API Keys
with open('credentials.json') as creds:    
    credentials = json.load(creds)

Retrieve The Credentials