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: object

Main 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.

  • client_secret (SecretStr | str | None)

Raises:

ConfigurationError – If the configuration is invalid.

Return type:

None

property session: Session[Any]

Public accessor for the underlying HTTP session.

classmethod from_env_file(path='.env')[source]

Create client from a specific env file.

Parameters:

path (str) – Path to env file (default: .env)

Returns:

Configured Upstox TOTP client

Return type:

Self

generate_request_id()[source]

Return the same request ID for the entire lifecycle of this client instance.

Return type:

str

generate_totp_secret()[source]

Generate a TOTP.

Return type:

str

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.

__enter__()[source]

Enter context manager.

Return type:

Self

__exit__(*args)[source]

Exit context manager and clean up.

Parameters:

args (object)

Return type:

None

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.

  • client_secret (SecretStr | str | None)

Raises:

ConfigurationError – If the configuration is invalid.

Return type:

None

Class Methods

classmethod UpstoxTOTP.from_env_file(path='.env')[source]

Create client from a specific env file.

Parameters:

path (str) – Path to env file (default: .env)

Returns:

Configured Upstox TOTP client

Return type:

Self

Instance Methods

TOTP Operations

UpstoxTOTP.generate_totp_secret()[source]

Generate a TOTP.

Return type:

str

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

UpstoxTOTP.generate_request_id()[source]

Return the same request ID for the entire lifecycle of this client instance.

Return type:

str

Context Manager Support

UpstoxTOTP.__enter__()[source]

Enter context manager.

Return type:

Self

UpstoxTOTP.__exit__(*args)[source]

Exit context manager and clean up.

Parameters:

args (object)

Return type:

None

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: BaseAPI

App token API.

Initialize the base API.

Parameters:

client (UpstoxTOTP)

client_id: str | None = None
get_user_id_and_user_type()[source]

Get user id and user type.

Return type:

UserIdAndUserType

generate_otp()[source]

Generate OTP.

Return type:

OTPGenerationResponse

validate_otp()[source]

Validate OTP.

Return type:

OTPValidationResponse

submit_pin()[source]

Submit PIN for 2FA.

Return type:

TwoFactorAuthenticationResponse

oauth_authorization()[source]

Two factor authentication.

Return type:

OAuthAuthorizationResponse

get_access_token()[source]

Get access token.

Return type:

AccessTokenResponse

The AppTokenAPI class handles the OAuth flow and access token generation.

Methods

AppTokenAPI.get_access_token()[source]

Get access token.

Return type:

AccessTokenResponse

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: object

Base 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

username

str

10-digit mobile number registered with Upstox

password

SecretStr

Upstox login password

pin_code

SecretStr

Upstox PIN code (4-6 digits)

totp_secret

SecretStr

TOTP secret key from authenticator app

client_id

str

API key from Upstox Developer App

client_secret

SecretStr

API secret from Upstox Developer App

redirect_uri

str

Redirect URI configured in Upstox app

Optional Parameters

Parameter

Type

Default

Description

debug

bool

False

Enable debug logging

sleep_time

int

1000

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

  1. Use environment variables for configuration in production

  2. Enable debug mode only in development

  3. Reuse client instances for better performance

  4. Use context managers for automatic cleanup

  5. Handle all exception types appropriately

  6. Validate configuration before deployment

  7. Monitor token expiry and refresh proactively

  8. Use connection pooling for high-volume applications

  9. Implement retry logic for resilient applications

  10. Clear sensitive data from memory when possible

See Also