Api not working

I am tring to get code for getting access_token but every time it gives error. I have deleted old app and crated new app but result is same

Thank you for getting in touch.

Could you please provide the sample code or the curl request you’re attempting to run to investigate?

Furthermore, if you’re facing any specific error, please provide the details of that error along with your code and mention your client ID.

I believe you are referencing the following API:

https://upstox.com/developer/api-documentation/get-token

import openpyxl
import upstox_client
from Config import *
import requests
import json

Set your API credentials

api_key = API_KEY
api_secret = SECRET_KEY
redirect_uri = ‘RURL’
code = ‘sQjJhP’

Get the access token

token_url = ‘https://api.upstox.com/index/dialog/authorize?apiKey={}&redirect_uri={}&response_type=code
token_data = {‘code’: code, ‘redirect_uri’: redirect_uri}
token_headers = {‘Content-Type’: ‘application/json’}
token_response = requests.post(token_url, data=json.dumps(token_data), headers=token_headers)
access_token = token_response.json()[‘access_token’]

Set the headers for the API request

headers = {
‘Authorization’: ‘Bearer {}’.format(access_token),
‘x-api-key’: api_key,
‘Content-Type’: ‘application/json’
}

Get holdings

holdings_url = ‘https://api.upstox.com/live/profile/positions
holdings_response = requests.get(holdings_url, headers=headers)
holdings = holdings_response.json()[‘data’]

Create a new Excel workbook

wb = openpyxl.Workbook()

Select the active worksheet

ws = wb.active

Write the headers

ws.append([‘Product’, ‘Symbol’, ‘Quantity’, ‘Average Price’, ‘LTP’, ‘Day Change’, ‘Day Change Percentage’])

Write the holdings data

for holding in holdings:
ws.append([
holding[‘product’],
holding[‘symbol’],
holding[‘quantity’],
holding[‘average_price’],
holding[‘ltp’],
holding[‘day_change’],
holding[‘day_change_percentage’]
])

Save the workbook

wb.save(‘holdings.xlsx’)

=================
I have stored all my credencial in file Config

OUT PUT OF IT IS
Traceback (most recent call last):
File “E:\chatGPT\myHOLDINGS.py”, line 18, in
access_token = token_response.json()[‘access_token’]
~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: ‘access_token’

Previously when we run url to get code it was given on redirece url and then ?code=“code”
while now I getting this
https://api-v2.upstox.com/login/authorization/redirect?code=sQjJhP&ucc=HN0693

and in body
{“status”:“error”,“errors”:[{“errorCode”:“UDAPI100016”,“message”:“Invalid Credentials”,“propertyPath”:null,“invalidValue”:null,“error_code”:“UDAPI100016”,“property_path”:null,“invalid_value”:null}]}

Hi @vgajre

Use this way maybe it will help you . just run one time and keep the access_token in any file
and use everywhere.

import requests
from playwright.sync_api import Playwright, sync_playwright
from urllib.parse import parse_qs,urlparse,quote
import pyotp
import requests
import config

API_KEY = config.API_KEY
SECRET_KEY = config.SECRET_KEY
RURL = ‘https://127.0.0.1:5050/
TOTP_KEY = config.TOTP_KEY
MOBILE_NO = config.MOBILE_NO
PIN = config.PIN

rurlEncode = quote(RURL,safe=“”)

AUTH_URL = f’https://api-v2.upstox.com/login/authorization/dialog?response_type={SECRET_KEY}&client_id={API_KEY}&redirect_uri={rurlEncode}

def getAccessToken(code):
url = ‘https://api-v2.upstox.com/login/authorization/token

headers = {
    'accept': 'application/json',
    'Api-Version': '2.0',
    'Content-Type': 'application/x-www-form-urlencoded'
}

data = {
    'code': code,
    'client_id': API_KEY,
    'client_secret': SECRET_KEY,
    'redirect_uri': RURL,
    'grant_type': 'authorization_code'
}

response = requests.post(url, headers=headers, data=data)
json_response = response.json()

# Access the response data
#print(f"access_token:  {json_response['access_token']}")
return {json_response['access_token']}

def run(playwright: Playwright) → str:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
with page.expect_request(f"{RURL}?code") as request:
page.goto(AUTH_URL,timeout = 0)
page.locator(“#mobileNum”).click()
page.locator(“#mobileNum”).fill(MOBILE_NO)
page.get_by_role(“button”, name=“Get OTP”).click()
page.locator(“#otpNum”).click()
otp = pyotp.TOTP(TOTP_KEY).now()
page.locator(“#otpNum”).fill(otp)
page.get_by_role(“button”, name=“Continue”).click()
page.get_by_label(“Enter 6-digit PIN”).click()
page.get_by_label(“Enter 6-digit PIN”).fill(PIN)
res = page.get_by_role(“button”, name=“Continue”).click()
page.wait_for_load_state()

url =    request.value.url 
print(f"Redirect Url with code : {url}")
parsed = urlparse(url)
code = parse_qs(parsed.query)['code'][0]
context.close()
browser.close()
return code

with sync_playwright() as playwright:
code = run(playwright)

access_token = getAccessToken(code)
access_code= list(access_token)[0]
file1 = open(“access_code.txt”,“w”)
file1.writelines(access_code)
file1.close()
print("access_token is genearated ")

Thanks

Thank you very much Rahul.

Your code works fine in browser address bar http://127.0.0.1/code=jTIYT9 also comes but

from url = request.value.url line it gives error as below I am tring to solve this error for last 15 days but not successfull pls help me. error I got as under
Traceback (most recent call last):
File “E:\chatGPT\myAccessToken.py”, line 67, in
with sync_playwright() as playwright:
File “C:\Users\vgajre\AppData\Local\Programs\Python\Python311\Lib\site-packages\playwright\sync_api_context_manager.py”, line 90, in exit
self._connection.stop_sync()
File “C:\Users\vgajre\AppData\Local\Programs\Python\Python311\Lib\site-packages\playwright_impl_connection.py”, line 279, in stop_sync
self.cleanup()
File “C:\Users\vgajre\AppData\Local\Programs\Python\Python311\Lib\site-packages\playwright_impl_connection.py”, line 295, in cleanup
callback.future.set_exception(Error(error_message))
asyncio.exceptions.InvalidStateError: invalid state

Hi

It is working fine for me . Maybe you are doing something wrong please check your code.
Please check below code

import requests
from playwright.sync_api import Playwright, sync_playwright
from urllib.parse import parse_qs,urlparse,quote
import pyotp
import requests
import config


#timeout=100


API_KEY = config.API_KEY
SECRET_KEY = config.SECRET_KEY
RURL = 'https://127.0.0.1:5050/'
TOTP_KEY = config.TOTP_KEY
MOBILE_NO = config.MOBILE_NO
PIN   = config.PIN


rurlEncode = quote(RURL,safe="")

AUTH_URL = f'https://api-v2.upstox.com/login/authorization/dialog?response_type={SECRET_KEY}&client_id={API_KEY}&redirect_uri={rurlEncode}'


def getAccessToken(code):
    url = 'https://api-v2.upstox.com/login/authorization/token'

    headers = {
        'accept': 'application/json',
        'Api-Version': '2.0',
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    data = {
        'code': code,
        'client_id': API_KEY,
        'client_secret': SECRET_KEY,
        'redirect_uri': RURL,
        'grant_type': 'authorization_code'
    }

    response = requests.post(url, headers=headers, data=data)
    json_response = response.json()

    # Access the response data
    #print(f"access_token:  {json_response['access_token']}")
    return {json_response['access_token']}

def run(playwright: Playwright) -> str:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()   
    with page.expect_request(f"*{RURL}?code*") as request:
        page.goto(AUTH_URL,timeout = 0)
        page.locator("#mobileNum").click()
        page.locator("#mobileNum").fill(MOBILE_NO)
        page.get_by_role("button", name="Get OTP").click()
        page.locator("#otpNum").click()
        otp = pyotp.TOTP(TOTP_KEY).now()
        page.locator("#otpNum").fill(otp)
        page.get_by_role("button", name="Continue").click()
        page.get_by_label("Enter 6-digit PIN").click()
        page.get_by_label("Enter 6-digit PIN").fill(PIN)
        res = page.get_by_role("button", name="Continue").click()
        page.wait_for_load_state()

    url =    request.value.url 
    print(f"Redirect Url with code : {url}")
    parsed = urlparse(url)
    code = parse_qs(parsed.query)['code'][0]
    context.close()
    browser.close()
    return code


with sync_playwright() as playwright:
    code = run(playwright)

access_token = getAccessToken(code)
access_code= list(access_token)[0]
file1 = open("access_code.txt","w")
file1.writelines(access_code)
file1.close()
print("access_token is genearated ")

Thanks

Right it works for every one but I can’t find why it is not working for me. Any way thanks for your help

@vgajre

I see that switching to the correct v2 endpoint generates the auth code. If it’s working in the browser but not in your custom code, the issue likely lies within the environment or code setup.

While we’re unable to provide direct support for custom code, our API documentation may offer some helpful pointers.

Let us know if you have any more questions.

Thanks!