Authentication: API Keys and OAuth
Bearer tokens, API key headers, OAuth2 flows for agent API access.
Why Authentication Matters for Agents
When your agent calls an external API, the server needs to know who is making the request. Authentication proves identity; authorization determines what you can do. Without proper auth, every request returns 401 Unauthorized and your agent can't do anything.
Two patterns dominate agent development: API keys and OAuth 2.0.
import requests
# Without auth — will get 401
response = requests.get('https://api.openai.com/v1/models')
print(response.status_code) # 401 Unauthorized
# With API key in header — works
headers = {'Authorization': 'Bearer sk-proj-abc123'}
response = requests.get(
'https://api.openai.com/v1/models',
headers=headers
)
print(response.status_code) # 200API Key in Authorization Header
The most common pattern is sending your API key in the Authorization header as a Bearer token. The word "Bearer" signals that whoever has this token is authorized — the server trusts the bearer of the key.
This is used by OpenAI, Anthropic, GitHub, and most modern APIs.
import requests
import os
api_key = os.environ['OPENAI_API_KEY']
response = requests.post(
'https://api.openai.com/v1/chat/completions',
headers={
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
},
json={
'model': 'gpt-4o-mini',
'messages': [{'role': 'user', 'content': 'Hello!'}]
}
)
print(response.json()['choices'][0]['message']['content'])All lessons in this course
- REST API Fundamentals for Agent Developers
- Authentication: API Keys and OAuth
- Handling API Responses and Errors
- Rate Limiting and Retry Logic