CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-upstox-python-sdk

The official Python client for communicating with the Upstox API, providing complete trading and investment platform functionality.

Overview
Eval results
Files

authentication.mddocs/

Authentication & User Management

Authentication and user account management functionality for the Upstox API, including OAuth2 authorization flow, token management, and user profile access.

Capabilities

OAuth2 Authorization Flow

The Upstox API uses OAuth2 for authentication. The complete flow involves redirecting users to authorize your application and exchanging authorization codes for access tokens.

def authorize(client_id: str, redirect_uri: str, api_version: str, state: str = None, scope: str = None) -> None:
    """
    Redirect user to Upstox authorization page.
    
    Parameters:
    - client_id: Your app's client ID from developer console
    - redirect_uri: URL to redirect after authorization (must match registered URL)
    - api_version: API version ('2.0')
    - state: Optional state parameter for security
    - scope: Optional scope parameter for permissions
    
    This method redirects the user to Upstox's authorization page.
    After authorization, user is redirected to redirect_uri with authorization code.
    """

def token(api_version: str, code: str = None, client_id: str = None, client_secret: str = None, redirect_uri: str = None, grant_type: str = None) -> TokenResponse:
    """
    Exchange authorization code for access token.
    
    Parameters:
    - api_version: API version ('2.0')
    - code: Authorization code from redirect
    - client_id: Your app's client ID
    - client_secret: Your app's client secret
    - redirect_uri: Same redirect URI used in authorize call
    - grant_type: Usually 'authorization_code'
    
    Returns:
    TokenResponse containing access_token and related info
    """

def logout(api_version: str) -> LogoutResponse:
    """
    Invalidate current session and access token.
    
    Parameters:
    - api_version: API version ('2.0')
    
    Returns:
    LogoutResponse confirming session termination
    """

Usage Example

import upstox_client
from upstox_client.api import LoginApi

# Step 1: Redirect user to authorization (usually done in web app)
login_api = LoginApi()
login_api.authorize(
    client_id='your_client_id',
    redirect_uri='https://yourapp.com/callback',
    api_version='2.0',
    state='random_state_value'
)

# Step 2: Exchange code for token (after user authorization)
token_response = login_api.token(
    api_version='2.0',
    code='authorization_code_from_redirect',
    client_id='your_client_id',
    client_secret='your_client_secret',
    redirect_uri='https://yourapp.com/callback',
    grant_type='authorization_code'
)

access_token = token_response.access_token

# Step 3: Use access token for API calls
configuration = upstox_client.Configuration()
configuration.access_token = access_token

# Step 4: Logout when done
logout_response = login_api.logout(api_version='2.0')

Indie User Token Management

Special token handling for indie (individual) users who may have different authentication requirements.

def init_token_request_for_indie_user(body: IndieUserTokenRequest, client_id: str) -> IndieUserInitTokenResponse:
    """
    Initialize token request for indie users.
    
    Parameters:
    - body: Token request details
    - client_id: Your app's client ID
    
    Returns:
    IndieUserInitTokenResponse with initialization details
    """

User Profile Management

Access user account information, profile details, and account capabilities.

def get_profile(api_version: str) -> GetProfileResponse:
    """
    Retrieve user profile information.
    
    Parameters:
    - api_version: API version ('2.0')
    
    Returns:
    GetProfileResponse containing user profile data
    """

def get_user_fund_margin(api_version: str, segment: str = None) -> GetUserFundMarginResponse:
    """
    Get user's fund and margin information.
    
    Parameters:
    - api_version: API version ('2.0')
    
    Returns:
    GetUserFundMarginResponse with fund and margin details
    """

Usage Example

from upstox_client.api import UserApi
from upstox_client import Configuration, ApiClient

# Setup authenticated API client
configuration = Configuration()
configuration.access_token = 'your_access_token'
api_client = ApiClient(configuration)
user_api = UserApi(api_client)

# Get user profile
profile_response = user_api.get_profile(api_version='2.0')
profile_data = profile_response.data

print(f"User ID: {profile_data.user_id}")
print(f"Name: {profile_data.user_name}")
print(f"Broker: {profile_data.broker}")
print(f"Active: {profile_data.is_active}")
print(f"Exchanges: {profile_data.exchanges}")
print(f"Products: {profile_data.products}")

# Get fund and margin information
fund_response = user_api.get_user_fund_margin(api_version='2.0')
fund_data = fund_response.data

print(f"Available margin: {fund_data.equity.available_margin}")
print(f"Used margin: {fund_data.equity.used_margin}")

Configuration & Client Setup

Configuration Class

class Configuration:
    def __init__(sandbox: bool = False) -> None:
        """
        Initialize configuration for API client.
        
        Parameters:
        - sandbox: Use sandbox environment if True, production if False
        """
    
    # Properties
    access_token: str  # OAuth access token
    api_key: dict  # API key configuration
    debug: bool  # Enable debug logging
    host: str  # API base URL
    logger_file: str  # Log file path
    
    def get_api_key_with_prefix(identifier: str) -> str:
        """Get API key with prefix for authentication"""
    
    def auth_settings() -> dict:
        """Get authentication settings for API calls"""
        
    def to_debug_report() -> str:
        """Generate debug information report"""

API Client

class ApiClient:
    def __init__(configuration: Configuration = None) -> None:
        """
        Initialize API client with configuration.
        
        Parameters:
        - configuration: Configuration object with auth details
        """
    
    def call_api(resource_path: str, method: str, path_params: dict = None, query_params: list = None, header_params: dict = None, body: object = None, post_params: list = None, files: dict = None, response_type: str = None, auth_settings: list = None, async_req: bool = None, _return_http_data_only: bool = None, collection_formats: dict = None, _preload_content: bool = True, _request_timeout: int = None) -> object:
        """
        Execute API request with authentication and error handling.
        
        Returns:
        API response object or data based on response_type
        """
    
    def set_default_header(header_name: str, header_value: str) -> None:
        """Set default header for all API requests"""

Usage Example

import upstox_client

# Production environment
config = upstox_client.Configuration(sandbox=False)
config.access_token = 'your_production_access_token'

# Sandbox environment for testing
sandbox_config = upstox_client.Configuration(sandbox=True)
sandbox_config.access_token = 'your_sandbox_access_token'

# Create API client
api_client = upstox_client.ApiClient(config)

# Enable debug logging
config.debug = True
config.logger_file = 'upstox_api.log'

Request/Response Types

class TokenRequest:
    code: str
    client_id: str
    client_secret: str
    redirect_uri: str
    grant_type: str

class TokenResponse:
    email: str
    exchanges: list[str]
    products: list[str]
    broker: str
    user_id: str
    user_name: str
    order_types: list[str]
    user_type: str
    poa: bool
    is_active: bool
    access_token: str
    extended_token: str

class IndieUserTokenRequest:
    # Token request details for indie users
    pass

class IndieUserInitTokenResponse:
    status: str
    data: IndieUserInitTokenData

class LogoutResponse:
    status: str
    message: str

class GetProfileResponse:
    status: str
    data: ProfileData

class ProfileData:
    user_id: str
    user_name: str
    user_type: str  # 'individual', 'business', etc.
    poa: bool  # Power of Attorney status
    is_active: bool
    broker: str
    exchanges: list[str]  # Available exchanges
    products: list[str]  # Available products
    order_types: list[str]  # Available order types
    email: str

class GetUserFundMarginResponse:
    status: str
    data: UserFundMarginData

class UserFundMarginData:
    # Dictionary structure with segment keys
    # Example keys: 'equity', 'commodity'
    pass  # Use dict[str, Margin] structure

class Margin:
    enabled: bool
    net: float
    available_margin: float
    used_margin: float
    category: str

Error Handling

from upstox_client.rest import ApiException

try:
    profile_response = user_api.get_profile(api_version='2.0')
except ApiException as e:
    print(f"API Exception: {e.status} - {e.reason}")
    print(f"Response body: {e.body}")

Common authentication errors:

  • 401 Unauthorized: Invalid or expired access token
  • 403 Forbidden: Insufficient permissions
  • 429 Too Many Requests: Rate limit exceeded

Install with Tessl CLI

npx tessl i tessl/pypi-upstox-python-sdk

docs

authentication.md

charges-analytics.md

index.md

market-data.md

order-management.md

portfolio-management.md

websocket-streaming.md

tile.json