Client API Reference
This section provides detailed documentation for the main client classes and methods.
UpstoxTOTP
- class upstox_totp.UpstoxTOTP(*, username=None, password=None, pin_code=None, totp_secret=None, client_id=None, client_secret=None, redirect_uri=None, debug=False, sleep_time=1000)[source]
Bases:
objectMain Upstox TOTP client.
Initialize the Upstox TOTP client.
- Parameters:
username (str | None) – The username for the Upstox account.
password (SecretStr | str | None) – The password for the Upstox account.
pin_code (SecretStr | str | None) – The pin code for the Upstox account.
totp_secret (SecretStr | str | None) – The TOTP secret for the Upstox account.
client_id (str | None) – The client ID for the Upstox account.
redirect_uri (str | None) – The redirect URI for the Upstox account.
debug (bool) – Whether to enable debug mode.
sleep_time (int) – The time to sleep between requests in milliseconds.
client_secret (SecretStr | str | None)
- Raises:
ConfigurationError – If the configuration is invalid.
- __init__(*, username=None, password=None, pin_code=None, totp_secret=None, client_id=None, client_secret=None, redirect_uri=None, debug=False, sleep_time=1000)[source]
Initialize the Upstox TOTP client.
- Parameters:
username (str | None) – The username for the Upstox account.
password (SecretStr | str | None) – The password for the Upstox account.
pin_code (SecretStr | str | None) – The pin code for the Upstox account.
totp_secret (SecretStr | str | None) – The TOTP secret for the Upstox account.
client_id (str | None) – The client ID for the Upstox account.
redirect_uri (str | None) – The redirect URI for the Upstox account.
debug (bool) – Whether to enable debug mode.
sleep_time (int) – The time to sleep between requests in milliseconds.
- Raises:
ConfigurationError – If the configuration is invalid.
- Return type:
None
- generate_request_id()[source]
Return the same request ID for the entire lifecycle of this client instance.
- Return type:
- reset_session()[source]
Reset the underlying HTTP session.
This will clear all headers, cookies, and session state without closing the session.
- Return type:
None
- property app_token: AppTokenAPI
App token management.
The main client class for handling Upstox TOTP authentication and token generation.
Constructor
- UpstoxTOTP.__init__(*, username=None, password=None, pin_code=None, totp_secret=None, client_id=None, client_secret=None, redirect_uri=None, debug=False, sleep_time=1000)[source]
Initialize the Upstox TOTP client.
- Parameters:
username (str | None) – The username for the Upstox account.
password (SecretStr | str | None) – The password for the Upstox account.
pin_code (SecretStr | str | None) – The pin code for the Upstox account.
totp_secret (SecretStr | str | None) – The TOTP secret for the Upstox account.
client_id (str | None) – The client ID for the Upstox account.
redirect_uri (str | None) – The redirect URI for the Upstox account.
debug (bool) – Whether to enable debug mode.
sleep_time (int) – The time to sleep between requests in milliseconds.
- Raises:
ConfigurationError – If the configuration is invalid.
- Return type:
None
Class Methods
Instance Methods
TOTP Operations
Session Management
- UpstoxTOTP.reset_session()[source]
Reset the underlying HTTP session.
This will clear all headers, cookies, and session state without closing the session.
- Return type:
None
Context Manager Support
Properties
- property UpstoxTOTP.session: Session[Any]
Public accessor for the underlying HTTP session.
Usage Examples
Basic Usage
from upstox_totp import UpstoxTOTP
# Initialize with auto-loaded configuration
upx = UpstoxTOTP()
# Generate access token
response = upx.app_token.get_access_token()
if response.success:
access_token = response.data.access_token
print(f"Token: {access_token}")
Manual Configuration
from upstox_totp import UpstoxTOTP
from pydantic import SecretStr
upx = UpstoxTOTP(
username="9876543210",
password=SecretStr("your-password"),
pin_code=SecretStr("your-pin"),
totp_secret=SecretStr("your-totp-secret"),
client_id="your-client-id",
client_secret=SecretStr("your-client-secret"),
redirect_uri="https://your-app.com/callback"
)
Environment File Loading
from upstox_totp import UpstoxTOTP
# Load from specific environment file
upx = UpstoxTOTP.from_env_file(".env.production")
Context Manager Usage
from upstox_totp import UpstoxTOTP
with UpstoxTOTP() as upx:
response = upx.app_token.get_access_token()
# Session automatically cleaned up
Session Customization
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
# Access underlying session
session = upx.session
session.timeout = (10, 30)
session.headers.update({'User-Agent': 'MyApp/1.0'})
# Reset session if needed
upx.reset_session()
TOTP Management
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
# Generate current TOTP
totp_code = upx.generate_totp_secret()
print(f"Current TOTP: {totp_code}")
AppTokenAPI
- class upstox_totp._api.app_token.AppTokenAPI(client)[source]
Bases:
BaseAPIApp token API.
Initialize the base API.
- Parameters:
client (UpstoxTOTP)
The AppTokenAPI class handles the OAuth flow and access token generation.
Methods
- AppTokenAPI.get_access_token()[source]
Get access token.
- Return type:
Usage Examples
Direct Usage
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
# Access the app_token instance
app_token = upx.app_token
# Generate access token
response = app_token.get_access_token()
Error Handling
from upstox_totp import UpstoxTOTP, UpstoxError
upx = UpstoxTOTP()
try:
response = upx.app_token.get_access_token()
if response.success:
token = response.data.access_token
else:
print(f"Error: {response.error}")
except UpstoxError as e:
print(f"Upstox API Error: {e}")
BaseAPI
- class upstox_totp._api.base.BaseAPI(client)[source]
Bases:
objectBase class for API endpoints.
Initialize the base API.
- Parameters:
client (UpstoxTOTP)
- __init__(client)[source]
Initialize the base API.
- Parameters:
client (UpstoxTOTP)
- Return type:
None
Base class for all API clients, providing common functionality.
Configuration Parameters
The UpstoxTOTP class accepts the following configuration parameters:
Required Parameters
Parameter |
Type |
Description |
|---|---|---|
|
|
10-digit mobile number registered with Upstox |
|
|
Upstox login password |
|
|
Upstox PIN code (4-6 digits) |
|
|
TOTP secret key from authenticator app |
|
|
API key from Upstox Developer App |
|
|
API secret from Upstox Developer App |
|
|
Redirect URI configured in Upstox app |
Optional Parameters
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
|
|
Enable debug logging |
|
|
|
Delay between requests (milliseconds) |
Configuration Validation
All parameters are validated using Pydantic models:
Username: Must be exactly 10 digits
Password: Must be non-empty string
PIN Code: Must be 4-6 digits
TOTP Secret: Must be valid base32 string
Client ID: Must be non-empty string
Client Secret: Must be non-empty string
Redirect URI: Must be valid URL format
Sleep Time: Must be between 100-10000 milliseconds
Error Handling
The client provides comprehensive error handling:
Configuration Errors
from upstox_totp import UpstoxTOTP, ConfigurationError
try:
upx = UpstoxTOTP(username="invalid") # Invalid format
except ConfigurationError as e:
print(f"Configuration error: {e}")
API Errors
from upstox_totp import UpstoxTOTP, UpstoxError
upx = UpstoxTOTP()
try:
response = upx.app_token.get_access_token()
except UpstoxError as e:
print(f"API error: {e}")
# Error includes helpful troubleshooting information
Network Errors
from upstox_totp import UpstoxTOTP
import requests
upx = UpstoxTOTP()
try:
response = upx.app_token.get_access_token()
except requests.RequestException as e:
print(f"Network error: {e}")
Thread Safety
The UpstoxTOTP client is not thread-safe by default. For concurrent usage:
Thread-Safe Usage
import threading
from upstox_totp import UpstoxTOTP
# Create separate instances for each thread
def worker():
upx = UpstoxTOTP() # Create new instance per thread
response = upx.app_token.get_access_token()
return response
# Use with threading
threads = []
for i in range(5):
thread = threading.Thread(target=worker)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
Session Sharing (Advanced)
import threading
from upstox_totp import UpstoxTOTP
# Shared session with thread-local storage
thread_local = threading.local()
def get_client():
if not hasattr(thread_local, 'upx'):
thread_local.upx = UpstoxTOTP()
return thread_local.upx
def worker():
upx = get_client()
response = upx.app_token.get_access_token()
return response
Performance Considerations
Session Reuse
from upstox_totp import UpstoxTOTP
# Reuse the same client instance for multiple calls
upx = UpstoxTOTP()
# Multiple token generations reuse the session
for i in range(5):
response = upx.app_token.get_access_token()
Connection Pooling
from upstox_totp import UpstoxTOTP
from requests.adapters import HTTPAdapter
upx = UpstoxTOTP()
# Configure connection pooling
adapter = HTTPAdapter(
pool_connections=10,
pool_maxsize=20
)
upx.session.mount("https://", adapter)
Memory Management
from upstox_totp import UpstoxTOTP
# Use context manager for automatic cleanup
with UpstoxTOTP() as upx:
response = upx.app_token.get_access_token()
# Session automatically cleaned up
# Or manually reset session
upx = UpstoxTOTP()
response = upx.app_token.get_access_token()
upx.reset_session() # Clear session data
Debugging
Enable Debug Mode
from upstox_totp import UpstoxTOTP
# Enable debug logging
upx = UpstoxTOTP(debug=True)
# Or via environment variable
# UPSTOX_DEBUG=true
Access Logs
import logging
from upstox_totp import UpstoxTOTP
# Configure logging to see debug information
logging.basicConfig(level=logging.DEBUG)
upx = UpstoxTOTP(debug=True)
response = upx.app_token.get_access_token()
Request/Response Inspection
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP(debug=True)
# Access session for custom logging
session = upx.session
# Add custom request/response logging
def log_request(request):
print(f"Request: {request.method} {request.url}")
def log_response(response):
print(f"Response: {response.status_code}")
# Hook into session events
session.hooks['response'].append(log_response)
Best Practices
Use environment variables for configuration in production
Enable debug mode only in development
Reuse client instances for better performance
Use context managers for automatic cleanup
Handle all exception types appropriately
Validate configuration before deployment
Monitor token expiry and refresh proactively
Use connection pooling for high-volume applications
Implement retry logic for resilient applications
Clear sensitive data from memory when possible
See Also
Data Models Reference - Response and data models
Error Handling Reference - Exception classes and error handling
Configuration Guide - Configuration guide
Advanced Usage Guide - Advanced usage patterns