0
# Authentication & User Management
1
2
Authentication and user account management functionality for the Upstox API, including OAuth2 authorization flow, token management, and user profile access.
3
4
## Capabilities
5
6
### OAuth2 Authorization Flow
7
8
The Upstox API uses OAuth2 for authentication. The complete flow involves redirecting users to authorize your application and exchanging authorization codes for access tokens.
9
10
```python { .api }
11
def authorize(client_id: str, redirect_uri: str, api_version: str, state: str = None, scope: str = None) -> None:
12
"""
13
Redirect user to Upstox authorization page.
14
15
Parameters:
16
- client_id: Your app's client ID from developer console
17
- redirect_uri: URL to redirect after authorization (must match registered URL)
18
- api_version: API version ('2.0')
19
- state: Optional state parameter for security
20
- scope: Optional scope parameter for permissions
21
22
This method redirects the user to Upstox's authorization page.
23
After authorization, user is redirected to redirect_uri with authorization code.
24
"""
25
26
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:
27
"""
28
Exchange authorization code for access token.
29
30
Parameters:
31
- api_version: API version ('2.0')
32
- code: Authorization code from redirect
33
- client_id: Your app's client ID
34
- client_secret: Your app's client secret
35
- redirect_uri: Same redirect URI used in authorize call
36
- grant_type: Usually 'authorization_code'
37
38
Returns:
39
TokenResponse containing access_token and related info
40
"""
41
42
def logout(api_version: str) -> LogoutResponse:
43
"""
44
Invalidate current session and access token.
45
46
Parameters:
47
- api_version: API version ('2.0')
48
49
Returns:
50
LogoutResponse confirming session termination
51
"""
52
```
53
54
#### Usage Example
55
56
```python
57
import upstox_client
58
from upstox_client.api import LoginApi
59
60
# Step 1: Redirect user to authorization (usually done in web app)
61
login_api = LoginApi()
62
login_api.authorize(
63
client_id='your_client_id',
64
redirect_uri='https://yourapp.com/callback',
65
api_version='2.0',
66
state='random_state_value'
67
)
68
69
# Step 2: Exchange code for token (after user authorization)
70
token_response = login_api.token(
71
api_version='2.0',
72
code='authorization_code_from_redirect',
73
client_id='your_client_id',
74
client_secret='your_client_secret',
75
redirect_uri='https://yourapp.com/callback',
76
grant_type='authorization_code'
77
)
78
79
access_token = token_response.access_token
80
81
# Step 3: Use access token for API calls
82
configuration = upstox_client.Configuration()
83
configuration.access_token = access_token
84
85
# Step 4: Logout when done
86
logout_response = login_api.logout(api_version='2.0')
87
```
88
89
### Indie User Token Management
90
91
Special token handling for indie (individual) users who may have different authentication requirements.
92
93
```python { .api }
94
def init_token_request_for_indie_user(body: IndieUserTokenRequest, client_id: str) -> IndieUserInitTokenResponse:
95
"""
96
Initialize token request for indie users.
97
98
Parameters:
99
- body: Token request details
100
- client_id: Your app's client ID
101
102
Returns:
103
IndieUserInitTokenResponse with initialization details
104
"""
105
```
106
107
### User Profile Management
108
109
Access user account information, profile details, and account capabilities.
110
111
```python { .api }
112
def get_profile(api_version: str) -> GetProfileResponse:
113
"""
114
Retrieve user profile information.
115
116
Parameters:
117
- api_version: API version ('2.0')
118
119
Returns:
120
GetProfileResponse containing user profile data
121
"""
122
123
def get_user_fund_margin(api_version: str, segment: str = None) -> GetUserFundMarginResponse:
124
"""
125
Get user's fund and margin information.
126
127
Parameters:
128
- api_version: API version ('2.0')
129
130
Returns:
131
GetUserFundMarginResponse with fund and margin details
132
"""
133
```
134
135
#### Usage Example
136
137
```python
138
from upstox_client.api import UserApi
139
from upstox_client import Configuration, ApiClient
140
141
# Setup authenticated API client
142
configuration = Configuration()
143
configuration.access_token = 'your_access_token'
144
api_client = ApiClient(configuration)
145
user_api = UserApi(api_client)
146
147
# Get user profile
148
profile_response = user_api.get_profile(api_version='2.0')
149
profile_data = profile_response.data
150
151
print(f"User ID: {profile_data.user_id}")
152
print(f"Name: {profile_data.user_name}")
153
print(f"Broker: {profile_data.broker}")
154
print(f"Active: {profile_data.is_active}")
155
print(f"Exchanges: {profile_data.exchanges}")
156
print(f"Products: {profile_data.products}")
157
158
# Get fund and margin information
159
fund_response = user_api.get_user_fund_margin(api_version='2.0')
160
fund_data = fund_response.data
161
162
print(f"Available margin: {fund_data.equity.available_margin}")
163
print(f"Used margin: {fund_data.equity.used_margin}")
164
```
165
166
## Configuration & Client Setup
167
168
### Configuration Class
169
170
```python { .api }
171
class Configuration:
172
def __init__(sandbox: bool = False) -> None:
173
"""
174
Initialize configuration for API client.
175
176
Parameters:
177
- sandbox: Use sandbox environment if True, production if False
178
"""
179
180
# Properties
181
access_token: str # OAuth access token
182
api_key: dict # API key configuration
183
debug: bool # Enable debug logging
184
host: str # API base URL
185
logger_file: str # Log file path
186
187
def get_api_key_with_prefix(identifier: str) -> str:
188
"""Get API key with prefix for authentication"""
189
190
def auth_settings() -> dict:
191
"""Get authentication settings for API calls"""
192
193
def to_debug_report() -> str:
194
"""Generate debug information report"""
195
```
196
197
### API Client
198
199
```python { .api }
200
class ApiClient:
201
def __init__(configuration: Configuration = None) -> None:
202
"""
203
Initialize API client with configuration.
204
205
Parameters:
206
- configuration: Configuration object with auth details
207
"""
208
209
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:
210
"""
211
Execute API request with authentication and error handling.
212
213
Returns:
214
API response object or data based on response_type
215
"""
216
217
def set_default_header(header_name: str, header_value: str) -> None:
218
"""Set default header for all API requests"""
219
```
220
221
### Usage Example
222
223
```python
224
import upstox_client
225
226
# Production environment
227
config = upstox_client.Configuration(sandbox=False)
228
config.access_token = 'your_production_access_token'
229
230
# Sandbox environment for testing
231
sandbox_config = upstox_client.Configuration(sandbox=True)
232
sandbox_config.access_token = 'your_sandbox_access_token'
233
234
# Create API client
235
api_client = upstox_client.ApiClient(config)
236
237
# Enable debug logging
238
config.debug = True
239
config.logger_file = 'upstox_api.log'
240
```
241
242
## Request/Response Types
243
244
```python { .api }
245
class TokenRequest:
246
code: str
247
client_id: str
248
client_secret: str
249
redirect_uri: str
250
grant_type: str
251
252
class TokenResponse:
253
email: str
254
exchanges: list[str]
255
products: list[str]
256
broker: str
257
user_id: str
258
user_name: str
259
order_types: list[str]
260
user_type: str
261
poa: bool
262
is_active: bool
263
access_token: str
264
extended_token: str
265
266
class IndieUserTokenRequest:
267
# Token request details for indie users
268
pass
269
270
class IndieUserInitTokenResponse:
271
status: str
272
data: IndieUserInitTokenData
273
274
class LogoutResponse:
275
status: str
276
message: str
277
278
class GetProfileResponse:
279
status: str
280
data: ProfileData
281
282
class ProfileData:
283
user_id: str
284
user_name: str
285
user_type: str # 'individual', 'business', etc.
286
poa: bool # Power of Attorney status
287
is_active: bool
288
broker: str
289
exchanges: list[str] # Available exchanges
290
products: list[str] # Available products
291
order_types: list[str] # Available order types
292
email: str
293
294
class GetUserFundMarginResponse:
295
status: str
296
data: UserFundMarginData
297
298
class UserFundMarginData:
299
# Dictionary structure with segment keys
300
# Example keys: 'equity', 'commodity'
301
pass # Use dict[str, Margin] structure
302
303
class Margin:
304
enabled: bool
305
net: float
306
available_margin: float
307
used_margin: float
308
category: str
309
```
310
311
## Error Handling
312
313
```python
314
from upstox_client.rest import ApiException
315
316
try:
317
profile_response = user_api.get_profile(api_version='2.0')
318
except ApiException as e:
319
print(f"API Exception: {e.status} - {e.reason}")
320
print(f"Response body: {e.body}")
321
```
322
323
Common authentication errors:
324
- `401 Unauthorized`: Invalid or expired access token
325
- `403 Forbidden`: Insufficient permissions
326
- `429 Too Many Requests`: Rate limit exceeded