⚠️ Pending Update · 2026-08-29 Verification · Content may be outdated, please refer to official docs Updated: 2026-08-29 · Status: Pending Verification
Introduction
A free API key may look worthless, but a leaked one can still drain your quota, be abused for phishing or spam, and get your account banned. This article provides an end-to-end key-protection checklist covering hardcoded-key defense, git hooks, KMS integration, and incident response.
架构图
Rule One: Never Hardcode
# ❌ Dangerous: key embedded in source
client = OpenAI(api_key="sk-or-v1-abc123...", base_url="...")
# ✅ Correct: read from env
import os
client = OpenAI(api_key=os.environ["OPENROUTER_API_KEY"], base_url="...")
Hardcoded keys are discoverable by code-search tools (like GitHub's full-site search) within seconds — the highest-risk mistake you can make.
Manage Local Keys with .env
pip install python-dotenv
Create .env in the project root:
OPENROUTER_API_KEY=sk-or-v1-...
GROQ_API_KEY=gsk_...
DEEPSEEK_API_KEY=sk-...
Load it in code:
from dotenv import load_dotenv
load_dotenv() # injects .env into os.environ
Critical: add .env to .gitignore:
# .gitignore
.env
.env.*
*.pem
secrets/
Git Hook to Prevent Accidental Commits
Install pre-commit and detect-secrets:
pip install pre-commit detect-secrets
pre-commit install
.pre-commit-config.yaml:
repos:
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args: ['--baseline', '.secrets.baseline']
Every commit is scanned for secrets and blocked if found. Add gitleaks for broader rules.
Production: Use a Secret Manager
Do not ship .env to production — use a KMS:
- AWS: Secrets Manager or Parameter Store
- GCP: Secret Manager
- Alibaba Cloud: KMS Credential Manager
- Self-hosted: HashiCorp Vault
Example (AWS Secrets Manager):
import boto3, json
def get_secret(name):
client = boto3.client("secretsmanager")
resp = client.get_secret_value(SecretId=name)
return json.loads(resp["SecretString"])["OPENROUTER_API_KEY"]
client = OpenAI(api_key=get_secret("prod/llm-keys"), base_url="...")
Operational Checklist
- Usage alerts: Turn on daily-budget email alerts on each provider dashboard.
- Separate keys per purpose: dev, prod, CI each use distinct keys so you can revoke surgically.
- Rotate regularly: Every 90 days to limit long-term exposure.
- IP restrictions: Some providers support allowlists. For OpenRouter, put a Cloudflare Worker in front for IP checks.
- Log redaction: Replace the
Authorizationheader with***when logging request bodies.
If a Key Leaks
- Immediately revoke the key on the provider dashboard.
- Review usage logs for abuse.
- Generate a new key and update every environment.
- Use
git filter-repoto scrub history and ask collaborators to re-clone.
Troubleshooting
.envalready committed: Revoke the key immediately, rungit rm --cached .env, then regenerate.- CI injection: Use GitHub Actions
secrets.OPENROUTER_API_KEYmapped to an env var in the workflow. - Team sharing: Share via 1Password or Vault — never paste screenshots in chat.
- Audit trail: Enable access logs in your KMS so every secret fetch is attributable.
Build these habits and your free APIs stay safe.
Best Practices
.envfile never enters Git: add.envto.gitignore; in CI use secret injection.- Use Vault/AWS Secrets Manager in production: key rotation, audit log, IAM permissions all in one.
- Pre-commit hook for key detection:
detect-secretsorgitleaksauto-scans staged files. - Quota alerts: daily cron checks
usage; alert at 30% remaining via email/SMS. - Per-environment key isolation: dev/ci/prod each get their own key; single leak has minimal blast radius.
🚀 Get Started: One-Click Free API Access
Want to call all the free models above with a single API key, no need to sign up for each provider? Apishare.cc provides a unified API Key — one key, 100+ models, free models at zero cost.
👉 Register on Apishare.cc → Get your unified API Key
📊 Want to see more free model rankings? Check out the Sep 2026 Free LLM API Rankings →
Get Started: APIShare Free API Directory
- 🆓 Claim your free credits:Register on APIShare · Sign in to console
- 🔍 Browse every free API and live ranking:APIShare Free API Directory
- 📊 See the leaderboard:Free LLM API Rankings
About the Free API Aggregator
The models covered in this guide are all served through the APIShare free API aggregator, which gives you one key for the whole catalog.
- Full model catalog: APIShare free API directory
- Sign up for a free trial key: Register and claim your API key