API Authentication
Most APIs require authentication to confirm who is making requests and what they are allowed to do. Agents must handle credentials securely and never expose them in logs or responses.
Authentication Methods
API Key in header: the most common method for service-to-service calls
Authorization: Bearer YOUR_API_KEY
X-API-Key: YOUR_API_KEY
Basic Auth: username and password encoded in Base64
Mostly used in older APIs — not recommended for new systems
OAuth 2.0: a token-based system where the agent exchanges credentials for a temporary access token
Used by Google, Salesforce, GitHub, and most enterprise APIs
Tokens expire and must be refreshed
HMAC Signatures: a request is signed with a secret key, and the signature is sent as a header
Used by AWS, Stripe, and high-security APIs
Secure Credential Handling
import os
import requests
# WRONG: Never hardcode credentials
# API_KEY = "sk-abc123..." # This will end up in version control!
# RIGHT: Load from environment variables
API_KEY = os.getenv("OPENAI_API_KEY")
if not API_KEY:
raise EnvironmentError("OPENAI_API_KEY environment variable not set")
def make_authenticated_request(endpoint: str, data: dict) -> dict:
"""Make an authenticated API request. Credentials never appear in logs."""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
try:
response = requests.post(endpoint, json=data, headers=headers, timeout=30)
if response.status_code == 401:
# Log that auth failed — but NEVER log the key itself
print("Authentication failed. Check API_KEY environment variable.")
return {"status": "error", "error_type": "auth",
"error": "Authentication failed"}
return {"status": "success", "data": response.json()}
except Exception as e:
return {"status": "error", "error": str(e)}
# Safe — credentials come from environment, not code
result = make_authenticated_request(
"https://api.example.com/data",
{"query": "top customers"}
)
print("Auth status:", result["status"])