import requests
import webbrowser
Step 1: Generate the Login URL
api_key = “8ca42000-8b4e-4207-xxxxxxxx”
redirect_uri = “https://sinsights.in/”
login_url = f"https://api-v2.upstox.com/login/authorization/dialog?response_type=code&client_id={api_key}&redirect_uri={redirect_uri}"
print(“Login URL:”, login_url)
Open the login URL in the default web browser
webbrowser.open(login_url)
Step 2: Capture the Authorization Code
Note: Manually capture the AUTH_CODE from the URL after login.
authorization_code = input("Enter the authorization code received from redirect URL: ")
Step 3: Exchange Authorization Code for Access Token
token_url = “https://api-v2.upstox.com/login/authorization/token”
token_params = {
“grant_type”: “authorization_code”,
“code”: authorization_code,
“client_id”: api_key,
“redirect_uri”: redirect_uri
}
headers = {
“Content-Type”: “application/x-www-form-urlencoded”
}
print(“Requesting access token…”)
response = requests.post(token_url, data=token_params, headers=headers)
if response.status_code == 200:
response_data = response.json()
access_token = response_data.get(“access_token”)
refresh_token = response_data.get(“refresh_token”)
print(“Access Token:”, access_token)
print(“Refresh Token:”, refresh_token)
else:
print(“Failed to obtain access token:”, response.json())
access_token = None
refresh_token = None
Step 4: Use the Access Token to Make API Requests
if access_token:
profile_url = “https://api-v2.upstox.com/user/profile”
headers = {
“Authorization”: f"Bearer {access_token}"
}
profile_response = requests.get(profile_url, headers=headers)
if profile_response.status_code == 200:
user_profile = profile_response.json()
print("User Profile:", user_profile)
else:
print("Failed to fetch user profile:", profile_response.json())
Step 5: Handle Token Refresh (Optional)
if refresh_token:
refresh_token_url = “https://api-v2.upstox.com/login/authorization/token”
refresh_params = {
“grant_type”: “refresh_token”,
“refresh_token”: refresh_token,
“client_id”: api_key,
“redirect_uri”: redirect_uri
}
refresh_response = requests.post(refresh_token_url, data=refresh_params, headers=headers)
if refresh_response.status_code == 200:
new_access_token = refresh_response.json().get("access_token")
print("New Access Token:", new_access_token)
else:
print("Failed to refresh access token:", refresh_response.json())
Requesting access token…
Failed to obtain access token: {‘status’: ‘error’, ‘errors’: [{‘errorCode’: ‘UDAPI10000’, ‘message’: ‘This request is not supported by Upstox API’, ‘propertyPath’: None, ‘invalidValue’: None, ‘error_code’: ‘UDAPI10000’, ‘property_path’: None, ‘invalid_value’: None}]}
someone help me please…