What is an API Key? Definition, Use, Security Best Practices
An API key is a unique string that identifies a calling app/user when accessing an API. Used for auth, rate limits, billing, weaker than OAuth.
What is an API key?
An API key is a unique string of characters that identifies and authenticates the application or user making a request to an API. It's the simplest form of API authentication: include the key in the request header (or sometimes query string), and the server checks it against a database to allow or deny the call.
API keys are commonly used for: identifying which app/team is calling, applying rate limits, tracking usage for billing, and basic authorization. They are simpler than OAuth but also weaker, anyone with the key can impersonate the holder.
What an API key looks like
# Long random string
API_KEY="sk_live_4eC39HqLyjWDarjtT1zdp7dc"
# Sometimes prefixed for identification
API_KEY="ghp_aBcD1234eFgH5678iJkL9012mNoP3456qRsT"How API keys are sent
| Method | Example | Notes |
|---|---|---|
| Authorization header | Authorization: Bearer YOUR_API_KEY | Most common, recommended |
| Custom header | X-API-Key: YOUR_API_KEY | Common pattern |
| Query string | ?api_key=YOUR_API_KEY | Less secure (logged in URLs) |
| Request body | JSON field | Rare for REST |
Header-based is preferred, avoids URL logs leaking the key.
API key vs other auth methods
| Method | Strength | When to use |
|---|---|---|
| API key | Low (single secret) | Server-to-server, internal, simple use cases |
| OAuth 2.0 | High (token-based, scoped) | User-facing apps, third-party access |
| JWT | Medium-high (signed, stateless) | Microservices, SPAs |
| mTLS | High (certificate-based) | Service-to-service, zero-trust |
| Basic Auth | Low (username/password) | Legacy; avoid in production |
| HMAC signing | High (signed requests) | Webhooks, AWS-style APIs |
API key generation example
// Node.js
import crypto from 'crypto';
function generateApiKey(prefix = 'sk_live_') {
return prefix + crypto.randomBytes(24).toString('hex');
}
const key = generateApiKey();
// sk_live_a1b2c3d4e5f6...
// Store HASH of key in DB, not key itself
const hash = crypto.createHash('sha256').update(key).digest('hex');
await db.apiKeys.insert({ user_id: userId, key_hash: hash });Critical: store hash, not the raw key. Even if your DB leaks, attackers can't use the keys.
API key security best practices
- Treat keys as secrets. Never commit to git, never paste in screenshots.
- Use environment variables.
API_KEY=...in.env(gitignored). - Rotate regularly. Every 90 days; immediately on any suspicion of leak.
- Scope with permissions. Read-only key for read-only ops; least privilege.
- IP allowlist. Restrict which IPs can use the key.
- Different keys per environment. Dev/staging/prod keys separate.
- Hash, don't store raw. bcrypt/SHA-256 the key in your DB.
- Show key once at creation. Force user to copy + secure it; don't display again.
- Rate-limit per key. Detect/contain compromised keys.
- Log key usage. Audit trail; detect anomalies.
- Revoke on demand. Killswitch for compromised keys.
Common API key pitfalls
- Keys in client-side code. Anyone can view source. Never put server-API keys in JS.
- Keys in git history. Even after deletion, git history retains them. Force rotation.
- Keys in URLs. Logged by proxies, browsers, analytics. Use headers.
- Single key for everything. Compromise = total breach. Use scoped keys.
- No rotation. Long-lived keys are higher risk.
- No rate limiting. Compromised key = unbounded abuse.
- Storing raw keys in DB. Breach exposes them all.
- Sharing keys via Slack/email. Keys end up in many places. Use a vault.
API key use cases
| Use case | Why API key works |
|---|---|
| Server-to-server auth | No user interaction needed |
| Public read APIs | Identify caller without full OAuth |
| Webhooks (sending side) | Authenticate the sender |
| Third-party integrations (server-side) | Simpler than OAuth flow |
| Internal microservice auth | If mTLS overkill |
FAQ: API keys
Are API keys secure?
Less than OAuth 2.0 or mTLS. They're single-secret bearer tokens, anyone with the key has access. Good for non-critical use cases; pair with rate limiting + IP allowlists.
API key vs OAuth: which to use?
API key for server-to-server, simple. OAuth for user-facing apps, third-party access on behalf of users, scoped permissions.
How do I rotate an API key?
Generate new key, deploy with both keys valid for a transition period, switch all clients to new, then revoke old.
Should API keys expire?
Yes, set expirations (90 days typical). Force renewal. Long-lived keys are leak risk.
Where do I store API keys?
Secrets manager (AWS Secrets Manager, HashiCorp Vault, Doppler) or environment variables. Never in code or git.
How do I detect a leaked API key?
GitHub secret scanning, gitleaks, truffleHog scan repos for committed keys. Monitor key usage patterns for anomalies.
Can I use API keys in mobile apps?
Risky, mobile binaries can be reverse-engineered. Better: OAuth with PKCE. If you must use API keys, scope them tightly + rotate often.
Test API-key-protected endpoints with LoadFocus
LoadFocus runs JMeter and k6 scripts that send API keys at scale, verifying rate limits + auth from 25+ regions. Sign up free at loadfocus.com/signup.
Related LoadFocus Tools
Put this concept into practice with LoadFocus, the same platform that powers everything you just read about.