Create a Python Config File for API Scripts

Community Champion
6 1 15.7K

A best practice you should adopt is storing sensitive information used in scripts in config files rather than directly in the scripts. This helps ensure a few important things:

  1. It is easier for you to make changes when you only have to change one file rather than multiple files.
  2. You can reference different configuration items like the production, beta, and test URLs of your Canvas instance. In my configuration file I have tokens for different roles and permissions as well as the different instance URLs.
  3. You are less likely to accidentally leak sensitive information. This is very important when you use a version control system, such as GitHub to share or archive your scripts. Unless you pay for a Github subscription to have private repositories, your code is publicly visible. There are people and groups constantly scanning Github and other publicly available version control systems for API tokens, keys, secrets, usernames, and passwords for exploitation. Luckily most version control systems include a way to ignore or prevent certain files from being uploaded to a repository. So you will want to add any config files containing sensitive information to that ignore list.

I use Python 3 as my go to scripting environment and a few years ago I adopted the use of configuration files using the configparser module​. One of the greatest strengths that configparser has is the ability to separate key value pairs in sections. In my config file I have an instance and an auth section. The instance section contains the different Canvas instance URLs appropriately named prod, beta, and test.


prod =

beta =

test =

catalog =


token = 1234567890……

teacher_token = 0987654321…..

student_token = 9045387230…..

You can name this anything you want, have any extension you want, and place it anywhere as well, e.g: config.ini, config/secrets.cfg. If you manage multiple instances you could create separate config files for each instance containing the different URLs and any tokens you need access to. In the event that a config file may be leaked or exposed, it will be isolated to that one file.

The code below is how I reference the config file, it makes it very convenient to drop this block of code into a new python file and I am ready to make some API calls.

from configparser import ConfigParser

config = ConfigParser()'config/config.ini')

token = config.get('auth', 'token')

domain = config.get('instance', 'prod')

headers = {'Authorization': 'Bearer {}'.format(token)}

Tags (3)
1 Comment