How do I keep an API key out of my code?

Read an API access code from an environment variable, check it without printing it, and save downloaded observations in a data folder of the project.

After this lesson, you can share a script that reads your FRED access code from your own computer’s settings and saves its downloads in the project’s data folder.

How do I read the access code without writing it in the script?

os.getenv("FRED_API_KEY") reads the access code from an environment variable, a named setting of your user account that Python can read, so the script holds only the variable’s name and works for anyone who sets their own code. A missing variable gives None, and a script prints at most the code’s length, never the code.

On Windows, a user variable is set under “Edit environment variables for your account”, and Python sees it after the editor restarts. patch.dict(os.environ, ...) sets a made-up variable only inside its with block, so the example leaves your settings unchanged. A free code comes from FRED’s website, and the lesson on web APIs uses it in a request.

The following box reads a variable that does not exist and then a made-up one.

import os
from unittest.mock import patch

print(os.getenv("COURSE_FRED_KEY"))
with patch.dict(os.environ, {"COURSE_FRED_KEY": "practice"}):
    access_code = os.getenv("COURSE_FRED_KEY")
    print(access_code is not None, len(access_code))
None
True 8

Where do I save the downloads?

Path.cwd() / "data" names a data folder inside the folder where Python runs, the project folder, and .mkdir(parents=True, exist_ok=True) creates it, with any missing folders above it, and accepts a folder that already exists. A file saved there, such as two months of the US unemployment rate, UNRATE, stays with the project.

/ joins the parts of a path, and naming a path creates nothing on disk. Path.home() names your user folder, for files that several projects share. The example uses the folder fred_keys_demo, emptied with shutil.rmtree at the start of the page, and the two rates of 4.2% and 4.3% are made up.

The following box creates the folder, saves the file and lists the folder.

import shutil
from pathlib import Path

project_data = Path.cwd() / "fred_keys_demo" / "data"
shutil.rmtree(project_data.parent, ignore_errors=True)
project_data.mkdir(parents=True, exist_ok=True)
(project_data / "unrate.csv").write_text("observation_date,UNRATE\n2024-01-01,4.20\n2024-02-01,4.30\n", encoding="utf-8")
print(project_data.is_dir(), [path.name for path in project_data.iterdir()])
True ['unrate.csv']

Your turn

Read unrate.csv from the data folder and print February’s rate. You should see 4.3.

index_col makes the dates the row labels.

import pandas as pd

print(pd.read_csv(project_data / "unrate.csv", index_col="observation_date").loc["2024-02-01", "UNRATE"])
4.3