Authentication & API Keys
Most APIs require authentication. Learn about API keys, Bearer tokens, OAuth basics, and how to keep credentials secure.
15 min•By Priygop Team•Updated 2026
API Authentication
API Authentication
import os
# Methods of API authentication:
# 1. API Key in query params
# requests.get("https://api.example.com/data?api_key=YOUR_KEY")
# 2. API Key in headers
# requests.get(url, headers={"X-API-Key": "YOUR_KEY"})
# 3. Bearer Token
# requests.get(url, headers={"Authorization": "Bearer YOUR_TOKEN"})
# 4. Basic Auth
# requests.get(url, auth=("username", "password"))
# SECURITY: Never hardcode API keys!
# Use environment variables:
# API_KEY = os.getenv("API_KEY")
# Demo: secure API client
class SecureAPIClient:
def __init__(self, api_key):
self._api_key = api_key
def _get_headers(self):
return {
"Authorization": f"Bearer {self._api_key}",
"Content-Type": "application/json",
}
def get(self, endpoint):
headers = self._get_headers()
# Mask the key for display
masked = self._api_key[:4] + "..." + self._api_key[-4:]
print(f" GET {endpoint}")
print(f" Auth: Bearer {masked}")
return {"status": 200, "data": "authenticated"}
# Usage with environment variable (simulated)
api_key = "sk_test_abc123xyz789"
client = SecureAPIClient(api_key)
result = client.get("/api/v1/users")
print(f" Result: {result}")
# .env file pattern:
print("\n=== .env file ===")
print("API_KEY=sk_test_abc123xyz789")
print("DATABASE_URL=postgres://localhost/mydb")
print("DEBUG=false")
print("\nLoad with: python-dotenv")
print("from dotenv import load_dotenv")
print("load_dotenv()")Tip
Tip
NEVER hardcode API keys in source code. Use environment variables or .env files. Add .env to .gitignore immediately.
Diagram
Loading diagram…
Technical diagram.
Common Mistake
Warning
Committing API keys to git. Even if you delete them later, they remain in git history. Rotate compromised keys immediately.
Quick Quiz
Practice Task
Note
(1) Store an API key in a .env file. (2) Load it with os.getenv(). (3) Add .env to .gitignore.