Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
API Security APIs APIs From Zero to Real-World API Testing & Automation Authentication Module 5 — API Authentication

API Keys Explained — How They Work and When to Use Them

Reviewed & accurate
AI Summary

What You'll Learn

  • What an API key is and how it works
  • Three common ways to send an API key
  • What API keys can and cannot do
  • When to use API keys vs other auth methods

Why This Matters

API keys are the most common form of API authentication for public and partner APIs. They are simple to issue, simple to use, and sufficient for many use cases. But they have real limitations — they cannot represent user identity, they cannot be scoped, and they are easy to leak. Knowing when to use them and when to upgrade is a core API skill.

Simple Explanation

An API key is a long string that identifies a client to the API. The client sends the key with every request; the server checks if the key is valid and applies any limits or permissions associated with it.

sk_test_4eC39HqLyjWDarjtT1zdp7dc

That's a typical API key format — a prefix (often identifying the environment), followed by a random string.

Real-World Analogy — A Gym Membership Card

An API key is like a gym membership card with a barcode. You scan it at the door; the system checks if the membership is active; if yes, the door unlocks. The card does not know who you are — anyone holding the card can use the gym. If you lose the card, anyone who finds it can get in until you report it lost.

API keys work the same way. They identify a client, not a user. Anyone with the key can use the API.

Three Ways to Send an API Key

Method 1 — In a header (most common)

GET /users HTTP/1.1
X-API-Key: sk_test_4eC39HqLyjWDarjtT1zdp7dc

Or sometimes:

Authorization: Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc

Method 2 — In a query parameter (less secure)

GET /users?api_key=sk_test_4eC39HqLyjWDarjtT1zdp7dc

Easy to test in a browser, but the key ends up in server logs, browser history, and analytics tools. Avoid for production.

Method 3 — In a custom header (varies by API)

GET /users HTTP/1.1
x-api-key: sk_test_4eC39HqLyjWDarjtT1zdp7dc

Many APIs define their own header name. Always check the API's docs.

Example — Calling an API with a Key (cURL)

curl -H "X-API-Key: sk_test_4eC39HqLyjWDarjtT1zdp7dc" \
  https://api.example.com/users

Example — Calling an API with a Key (Postman)

  1. Click the Authorization tab.
  2. Type: API Key.
  3. Key: X-API-Key.
  4. Value: sk_test_4eC39HqLyjWDarjtT1zdp7dc.
  5. Add to: Header.

Postman adds the header to every request in this tab automatically.

What API Keys Can Do

  • Identify the client (which app, which developer).
  • Apply rate limits (100 requests/hour for free tier, 10000/hour for paid).
  • Enable/disable access — revoke the key, access stops immediately.
  • Track usage for billing and analytics.

What API Keys Cannot Do

  • Identify a specific user. The key belongs to the app, not the user. If multiple users use your app, the API cannot tell them apart.
  • Limit what operations the client can do. Most API keys grant full access — there's usually no per-operation scope.
  • Expire automatically. Keys are typically long-lived until manually revoked.
  • Be safely sent in URLs. URLs are logged everywhere; keys in URLs leak.

API Keys vs Tokens

AspectAPI KeyToken (e.g., JWT)
IdentifiesThe client/appA specific user
LifetimeLong (months/years)Short (minutes/hours)
ScopesUsually all-or-nothingFine-grained (read:posts, write:comments)
ExpirationManual revocationAutomatic via exp claim
User contextNoneYes — user ID, roles, etc.
RevocationEasy (delete the key)Harder — token may still be valid until expiry

When to Use API Keys

  • Server-to-server APIs where the client is a trusted backend.
  • Public APIs with rate limits (OpenWeatherMap, NewsAPI).
  • Simple partner integrations where the partner's app needs access.
  • Internal microservices behind a firewall.

When NOT to Use API Keys

  • Apps acting on behalf of users. Use OAuth 2.0 (covered in lesson 30).
  • Operations that need user-specific permissions. A key cannot say "this user can read but not write".
  • Frontend apps. Keys are easily stolen from frontend code. Use a backend proxy.
  • High-security operations (payments, account changes). Use short-lived tokens.

Best Practices for API Key Security

  1. Never commit keys to git. Use environment variables or a secrets manager.
  2. Never put keys in frontend code. Browser dev tools expose them instantly.
  3. Never put keys in URLs. They end up in logs everywhere.
  4. Rotate keys periodically. Generate a new one, switch the app, then revoke the old one.
  5. Use different keys for different environments. Test key for dev, production key for prod.
  6. Set per-key rate limits. Limits the blast radius if a key leaks.
  7. Monitor key usage. Set up alerts for unusual patterns.

Common Mistakes

  1. Sending the key in a URL query parameter. Convenient for testing, terrible for production. Use a header.
  2. Hard-coding keys in source files. Use env vars: process.env.API_KEY.
  3. Using one key for everything. Different environments, different services, different keys. Limit blast radius.
  4. Assuming API keys identify users. They do not. They identify clients. For users, use OAuth.
  5. Not rotating keys. A key used for 5 years is a key that's probably leaked somewhere.

Practical Exercise (5 minutes)

  1. Sign up for a free API key on any service that offers one (OpenWeatherMap, NewsAPI, NASA APIs).
  2. Use cURL to call the API with the key in a header.
  3. Try the same call with the key in a query parameter — observe that it works but is less secure.
  4. Try the same call without the key — observe the 401 error.

Mini Challenge

Design an API key system for a SaaS API. Decide: (1) what format are keys? (2) where do clients send them? (3) what rate limits apply? (4) how do clients rotate keys? (5) what happens if a key is compromised? Write a one-page design doc.

Key Takeaways

  • An API key is a long string that identifies a client to the API.
  • Send keys in headers (X-API-Key or Authorization: Bearer), not URLs.
  • API keys identify clients, not users. They cannot enforce user-level permissions.
  • Use API keys for server-to-server or partner APIs. Use OAuth for user-facing apps.
  • Never commit keys to git, never put them in frontend code, rotate them periodically.
Course continuity
Previously: Lesson 26 distinguished authentication from authorization.
Today: You learned the simplest authentication method — API keys.
Next: Lesson 28 covers Basic Authentication and Bearer tokens.

FAQ

Are API keys secure?

Secure enough for many uses, but not for high-security operations. They are long-lived, often have full access, and cannot identify users. For apps acting on behalf of users, use OAuth 2.0 instead.

What should I do if my API key leaks?

Revoke it immediately in the API provider's dashboard. Generate a new key, update your app to use it, and audit logs to see if the leaked key was used maliciously. Most providers log usage per key.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments