Nexus Learn

Log in · Create free account

Module 6: Calling an AI service from Python · 8 min

Keeping API keys safe

An API key is a secret password that proves who you are, and usually your account pays for its use. If it leaks, other people can spend your money.

  • Never type the key into your code or paste it into a chat, a forum or GitHub.
  • Keep it in an environment variable and read it in code.
  • Add secret files such as .env to .gitignore.
  • Use a separate key for each project, with a spending limit, and delete a key if it leaks.
import os

api_key = os.environ.get("MY_AI_KEY")
if not api_key:
    raise SystemExit("Set the MY_AI_KEY environment variable first")
(free account needed to save progress)

← Web requests and APIs  |  Sending a prompt to a model →