A Python OAuth 1.0 library providing comprehensive authentication, signing, and client capabilities.
—
Automated OAuth-enabled HTTP client that extends httplib2 to handle request signing transparently. The Client class provides a simple interface for making OAuth-authenticated HTTP requests without manual signature handling.
The Client class wraps httplib2.Http and automatically signs all requests using OAuth credentials. It supports all HTTP methods and handles both form-encoded and regular request bodies.
class Client:
def __init__(self, consumer, token=None, **kwargs):
"""
Initialize OAuth HTTP client.
Args:
consumer: Consumer credentials (required)
token: Token credentials (optional, for authenticated requests)
**kwargs: Additional arguments passed to httplib2.Http
Raises:
ValueError: If consumer is invalid or token is invalid
"""
def set_signature_method(self, method):
"""
Set signature method for request signing.
Args:
method: SignatureMethod instance
Raises:
ValueError: If signature method is invalid
"""
def request(self, uri: str, method: str = "GET", body: bytes = b'', headers: dict = None, redirections: int = 5, connection_type=None) -> tuple:
"""
Make OAuth-signed HTTP request.
Args:
uri (str): Request URI
method (str): HTTP method (GET, POST, PUT, DELETE, etc.)
body (bytes): Request body
headers (dict): HTTP headers
redirections (int): Maximum number of redirects to follow
connection_type: Connection type for httplib2
Returns:
tuple: (response, content) where response contains status and headers,
content contains response body
"""import oauth2
# Set up credentials
consumer = oauth2.Consumer('your_consumer_key', 'your_consumer_secret')
token = oauth2.Token('user_token_key', 'user_token_secret')
# Create client
client = oauth2.Client(consumer, token)
# Make authenticated GET request
response, content = client.request('https://api.example.com/user/profile')
print(f"Status: {response.status}")
print(f"Content: {content.decode('utf-8')}")import oauth2
consumer = oauth2.Consumer('consumer_key', 'consumer_secret')
token = oauth2.Token('token_key', 'token_secret')
client = oauth2.Client(consumer, token)
# Form data
form_data = 'name=John&email=john@example.com'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# Make POST request
response, content = client.request(
uri='https://api.example.com/users',
method='POST',
body=form_data.encode('utf-8'),
headers=headers
)
print(f"Response: {response.status}")
print(f"Location: {response.get('location', 'N/A')}")import oauth2
import json
consumer = oauth2.Consumer('consumer_key', 'consumer_secret')
token = oauth2.Token('token_key', 'token_secret')
client = oauth2.Client(consumer, token)
# JSON data
data = {'name': 'John Doe', 'email': 'john@example.com'}
json_body = json.dumps(data).encode('utf-8')
headers = {'Content-Type': 'application/json'}
# Make JSON POST request
response, content = client.request(
uri='https://api.example.com/users',
method='POST',
body=json_body,
headers=headers
)
if response.status == 201:
result = json.loads(content.decode('utf-8'))
print(f"Created user: {result}")import oauth2
# Consumer-only authentication (no user token)
consumer = oauth2.Consumer('consumer_key', 'consumer_secret')
client = oauth2.Client(consumer) # No token provided
# Make request signed only with consumer credentials
response, content = client.request('https://api.example.com/public_data')
print(f"Public data: {content.decode('utf-8')}")import oauth2
consumer = oauth2.Consumer('consumer_key', 'consumer_secret')
token = oauth2.Token('token_key', 'token_secret')
client = oauth2.Client(consumer, token)
# Use PLAINTEXT signature method instead of default HMAC-SHA1
plaintext_method = oauth2.SignatureMethod_PLAINTEXT()
client.set_signature_method(plaintext_method)
response, content = client.request('https://api.example.com/data')import oauth2
import httplib2
consumer = oauth2.Consumer('consumer_key', 'consumer_secret')
token = oauth2.Token('token_key', 'token_secret')
client = oauth2.Client(consumer, token)
try:
response, content = client.request('https://api.example.com/protected')
if response.status == 401:
print("Authentication failed - check credentials")
elif response.status == 403:
print("Access forbidden - insufficient permissions")
elif response.status >= 400:
print(f"Client error: {response.status}")
elif response.status >= 500:
print(f"Server error: {response.status}")
else:
print(f"Success: {content.decode('utf-8')}")
except httplib2.HttpLib2Error as e:
print(f"HTTP error: {e}")
except oauth2.Error as e:
print(f"OAuth error: {e}")import oauth2
import httplib2
# Configure httplib2 options
consumer = oauth2.Consumer('consumer_key', 'consumer_secret')
token = oauth2.Token('token_key', 'token_secret')
# Pass httplib2 configuration
client = oauth2.Client(
consumer,
token,
timeout=30,
disable_ssl_certificate_validation=False,
ca_certs='/path/to/cacerts.txt'
)
# Make request with custom headers and redirects
headers = {
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json'
}
response, content = client.request(
uri='https://api.example.com/data',
method='GET',
headers=headers,
redirections=3 # Limit redirects
)The Client automatically detects form-encoded content and handles parameter extraction for signing:
# Form data is automatically parsed for OAuth signing
form_body = 'param1=value1¶m2=value2'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# Client extracts form parameters for signature base string
response, content = client.request(
uri='https://api.example.com/endpoint',
method='POST',
body=form_body.encode('utf-8'),
headers=headers
)The Client automatically:
The Client extends httplib2.Http, so it supports all httplib2 features including:
Install with Tessl CLI
npx tessl i tessl/pypi-oauth2