← Back to articles
Detailed Usage

Security and Key Management for Free APIs

⚠️ 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.

架构图

flowchart TD A[API Key Security] --> B[.env file - local dev] A --> C[Secret manager - production] A --> D[Git hooks - prevent leak] A --> E[Quota watchdog - detect abuse] B --> F[Single source of truth] C --> F D --> F E --> F F --> G[No key in Git, no key leaked]

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 Authorization header with *** when logging request bodies.

If a Key Leaks

  1. Immediately revoke the key on the provider dashboard.
  2. Review usage logs for abuse.
  3. Generate a new key and update every environment.
  4. Use git filter-repo to scrub history and ask collaborators to re-clone.

Troubleshooting

  • .env already committed: Revoke the key immediately, run git rm --cached .env, then regenerate.
  • CI injection: Use GitHub Actions secrets.OPENROUTER_API_KEY mapped 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

  • .env file never enters Git: add .env to .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-secrets or gitleaks auto-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


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.

More in this category

Free AI Content Moderation API Guide 2026: Llama Guard 3 vs Perspective vs OpenAIFree OCR and Document Parsing API in PracticeIntegrating Free APIs into Your Local IDEConnecting Free Models to OpenCode in PracticeApplying for an OpenRouter API Key and Understanding Pricing

Ready to use free LLM APIs?

APIShare aggregates free AI APIs worldwide — sign up and get bonus credits.