Data Models Reference
This section documents all the data models and response types used in the Upstox TOTP SDK.
Response Models
AccessTokenResponse
- class upstox_totp.models.AccessTokenResponse(*, success, data=None, error=None)[source]
Bases:
ResponseBase[AccessTokenData]Response model for access token endpoint.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Response model for access token generation.
Fields:
success(bool): Whether the request was successfuldata(AccessTokenData | None): Token data if successfulerror(dict | None): Error details if request failed
Example:
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
response = upx.app_token.get_access_token()
if response.success and response.data:
print(f"Token: {response.data.access_token}")
print(f"User: {response.data.user_name}")
else:
print(f"Error: {response.error}")
AccessTokenData
- class upstox_totp.models.AccessTokenData(*, email, exchanges, products, broker, user_id, user_name, order_types, user_type, poa, ddpi, is_active, access_token, extended_token=None)[source]
Bases:
BaseModelCreate a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Contains the actual access token data and user information.
Key Fields:
access_token(str): The JWT access token for API callsuser_id(str): Unique user identifieruser_name(str): Display name of the useremail(str): User’s email addressbroker(str): Broker name (typically “UPSTOX”)user_type(str): Account type (e.g., “individual”)products(List[str]): Available product typesexchanges(List[str]): Available exchangesis_active(bool): Whether the account is active
Example:
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
response = upx.app_token.get_access_token()
if response.success:
data = response.data
print(f"Access Token: {data.access_token}")
print(f"User ID: {data.user_id}")
print(f"User Name: {data.user_name}")
print(f"Email: {data.email}")
print(f"Products: {', '.join(data.products)}")
print(f"Exchanges: {', '.join(data.exchanges)}")
OTPGenerationResponse
- class upstox_totp.models.OTPGenerationResponse(*, success, data=None, error=None)[source]
Bases:
ResponseBase[OTPData]Response model for OTP generation endpoint.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Response model for OTP generation during authentication flow.
OTPValidationResponse
- class upstox_totp.models.OTPValidationResponse(*, success, data=None, error=None)[source]
Bases:
ResponseBase[OTPValidationData]Response model for OTP validation endpoint.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Response model for OTP validation.
OTPValidationData
- class upstox_totp.models.OTPValidationData(*, message, userType, userProfile, isSecretPinSet)[source]
Bases:
BaseModelCreate a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
message (str)
userType (str)
userProfile (OTPValidationUserProfile)
isSecretPinSet (bool)
- userProfile: OTPValidationUserProfile
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Contains OTP validation result data.
OTPValidationUserProfile
- class upstox_totp.models.OTPValidationUserProfile(*, profileId, userId, firstName, lastName, avatarUrl=None)[source]
Bases:
BaseModelCreate a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
User profile information returned during OTP validation.
TwoFactorAuthenticationData
- class upstox_totp.models.TwoFactorAuthenticationData(*, redirectUri=None, userType, customerStatus, appStatus=None, refreshTokenExpiry, isPlusPlanFastWebsocketEnabled, isNewRefreshTokenCreated, isExternalClientOAuthApp)[source]
Bases:
BaseModelCreate a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Two-factor authentication data model.
Base Models
ResponseBase
- class upstox_totp.models.ResponseBase(*, success, data=None, error=None)[source]
-
Base response model for Upstox API.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Base response class that all API responses inherit from.
Common Fields:
success(bool): Indicates if the request was successfuldata(T | None): Response data (varies by endpoint)error(dict | None): Error information if request failed
Usage Pattern:
# All responses follow this pattern
response = api_method()
if response.success:
# Use response.data
data = response.data
else:
# Handle response.error
error = response.error
Model Validation
All models use Pydantic v2 for strict validation and type checking.
Validation Features
Strict mode: No automatic type coercion
Field validation: All fields are validated according to their types
Custom validators: Special validation rules for specific fields
Error messages: Clear, helpful error messages for validation failures
Example Validation
from upstox_totp.models import AccessTokenData
from pydantic import ValidationError
try:
# This will fail validation
data = AccessTokenData(
access_token="", # Empty string not allowed
user_id=123, # Should be string, not int
# ... other fields
)
except ValidationError as e:
print(f"Validation error: {e}")
Serialization
JSON Serialization
All models support JSON serialization:
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
response = upx.app_token.get_access_token()
if response.success:
# Serialize to JSON
json_data = response.model_dump_json(indent=2)
print(json_data)
# Serialize to dict
dict_data = response.model_dump()
print(dict_data)
Custom Serialization
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
response = upx.app_token.get_access_token()
if response.success:
# Exclude sensitive fields
safe_data = response.model_dump(
exclude={'access_token'}, # Don't include token
exclude_none=True, # Skip None values
exclude_unset=True # Skip unset values
)
print(safe_data)
Deserialization
From JSON
from upstox_totp.models import AccessTokenResponse
import json
# From JSON string
json_str = '{"success": true, "data": {...}, "error": null}'
response = AccessTokenResponse.model_validate_json(json_str)
# From dict
data_dict = json.loads(json_str)
response = AccessTokenResponse.model_validate(data_dict)
Error Handling
from upstox_totp.models import AccessTokenResponse
from pydantic import ValidationError
try:
response = AccessTokenResponse.model_validate_json(invalid_json)
except ValidationError as e:
print(f"Failed to parse response: {e}")
Field Types
Common Field Types
Type |
Example |
Description |
|---|---|---|
|
|
String fields |
|
|
Boolean flags |
|
|
Integer numbers |
|
|
List of strings |
|
|
Dictionary objects |
|
|
ISO datetime strings |
|
|
Nullable fields |
Custom Field Types
The SDK defines several custom field types:
SecretStr: For sensitive data that’s masked in logs
EmailStr: Validates email format
HttpUrl: Validates URL format
from pydantic import SecretStr, EmailStr, HttpUrl
# SecretStr usage
password = SecretStr("secret")
print(password) # SecretStr('**********')
print(password.get_secret_value()) # "secret"
Model Examples
Complete Access Token Example
from upstox_totp import UpstoxTOTP
upx = UpstoxTOTP()
response = upx.app_token.get_access_token()
if response.success and response.data:
token_data = response.data
print("=== Access Token Information ===")
print(f"Token: {token_data.access_token[:20]}...")
print(f"User ID: {token_data.user_id}")
print(f"Name: {token_data.user_name}")
print(f"Email: {token_data.email}")
print(f"Broker: {token_data.broker}")
print(f"Type: {token_data.user_type}")
print(f"Active: {token_data.is_active}")
print("\n=== Available Products ===")
for product in token_data.products:
print(f"- {product}")
print("\n=== Available Exchanges ===")
for exchange in token_data.exchanges:
print(f"- {exchange}")
Error Response Example
from upstox_totp import UpstoxTOTP, UpstoxError
upx = UpstoxTOTP()
try:
response = upx.app_token.get_access_token()
except UpstoxError as e:
print("=== Error Response ===")
print(f"Error: {e}")
# Access underlying response if available
if hasattr(e, 'response'):
error_response = e.response
if hasattr(error_response, 'error') and error_response.error:
print(f"Error Code: {error_response.error.get('code')}")
print(f"Error Message: {error_response.error.get('message')}")
Working with Raw Responses
from upstox_totp import UpstoxTOTP
import requests
upx = UpstoxTOTP()
# Get token
response = upx.app_token.get_access_token()
token = response.data.access_token
# Use token for raw API calls
headers = {'Authorization': f'Bearer {token}'}
raw_response = requests.get(
'https://api.upstox.com/v2/user/profile',
headers=headers
)
# Parse response manually
if raw_response.status_code == 200:
profile_data = raw_response.json()
print(f"Raw API response: {profile_data}")
Model Inheritance
Response Hierarchy
All response models inherit from ResponseBase:
ResponseBase
├── AccessTokenResponse
├── OTPGenerationResponse
├── OTPValidationResponse
└── OAuthAuthorizationResponse
Custom Response Models
You can create custom response models:
from upstox_totp.models import ResponseBase
from pydantic import BaseModel
from typing import Optional
class CustomData(BaseModel):
message: str
timestamp: str
class CustomResponse(ResponseBase[CustomData]):
pass
# Usage
response = CustomResponse(
success=True,
data=CustomData(message="Hello", timestamp="2023-01-01"),
error=None
)
Best Practices
Always check success flag before accessing data
Handle validation errors when creating models manually
Use type hints for better IDE support
Serialize safely by excluding sensitive fields
Validate input data before creating models
Use model methods for serialization/deserialization
Handle None values appropriately
Log errors for debugging purposes
Performance Considerations
Model Creation
# Efficient - direct model creation
response = AccessTokenResponse(success=True, data=data, error=None)
# Less efficient - JSON parsing
response = AccessTokenResponse.model_validate_json(json_string)
Memory Usage
# Clear large objects when done
response = upx.app_token.get_access_token()
token = response.data.access_token
# Clear response to free memory
del response
Caching Models
from functools import lru_cache
@lru_cache(maxsize=100)
def parse_response(json_data: str) -> AccessTokenResponse:
return AccessTokenResponse.model_validate_json(json_data)
See Also
Client API Reference - Client API reference
Error Handling Reference - Error handling
Configuration Guide - Configuration guide
Basic Usage Examples - Usage examples