Urgent: Sandbox API - Persistent 401 Unauthorized (Error UDAPI100050) on Order Placement Despite Valid Token

Dear Upstox API Support Team,

I hope this message finds you well.

I am a developer actively testing a trading application in your Sandbox environment using the official upstox-python-sdk. I am facing a persistent and critical issue where all order placement calls are being rejected with a 401 Unauthorized error, and I have exhausted all possible client-side troubleshooting steps.

Summary of the Issue:

  • My script successfully connects to the Sandbox environment using the permanent access_token generated from my developer console. The initial client configuration is successful.

  • However, when the script attempts to place an order using the place_order function, the API server rejects the request with the specific error code UDAPI100050: Invalid token used to access API.

  • This is happening during live market hours.

My Sandbox App Details:

  • API Key (Client ID): af0ab2a6-a8d4-4984-a24a-cdf5eb057d2c

  • Redirect URI: https://127.0.0.1

  • User ID / UCC: [Your UCC ID, e.g., 761432]

Troubleshooting Steps Already Taken:

I have diligently followed all standard procedures to resolve this, without success:

  1. Token Regeneration: I have regenerated the Sandbox access_token multiple times, most recently today, to ensure it is fresh and valid. The token’s expiry is well in the future. The error persists even with a brand new token.

  2. Credential Verification: I have meticulously verified that the api_key and api_secret in my configuration match the Sandbox App in my console.

  3. Environment Confirmation: My script is correctly configured to connect to the Sandbox host (https://api-sandbox.upstox.com) by setting ENVIRONMENT = “SANDBOX”.

  4. SDK Version: I am using a recent version of the upstox-python-sdk, and the code structure for placing orders appears to be correct as per the library’s requirements.

Code Snippet for Order Placement:

For your reference, this is the core function call that is failing. The client object is successfully authenticated and configured before this call is made.

codePython

def place_order(client, instrument, transaction_type, order_type="MARKET", price=0):
    """A generalized function to place buy or sell orders."""
    if not client or not instrument:
        logging.error("Cannot place order, client or instrument is missing.")
        return None

    order_api = upstox_client.OrderApi(client)
    try:
        # This is the call that receives the 401 Unauthorized error
        api_response = order_api.place_order(
            body=upstox_client.PlaceOrderRequest(
                quantity=int(instrument['lot_size']),
                product="I",
                validity="DAY",
                price=price,
                order_type=order_type,
                instrument_token=instrument['instrument_key'],
                transaction_type=transaction_type,
                disclosed_quantity=0,
                trigger_price=0,
                is_amo=False
            ),
            api_version="v2"
        )
        logging.info(f"{transaction_type} order placed for {instrument['trading_symbol']}. Order ID: {api_response.data.order_id}")
        return api_response.data.order_id
    except ApiException as e:
        logging.error(f"Failed to place {transaction_type} order for {instrument['trading_symbol']}: {e}")
        return None

Given that the initial client configuration succeeds but subsequent order calls fail with an “Invalid token” error, this strongly suggests a server-side issue, possibly related to the provisioning of my Sandbox account or a permissions mismatch on your backend for the order placement endpoints.

Could you please investigate the configuration and permissions for my Sandbox app and account to identify why a seemingly valid token is being rejected by the order placement API?

I have attached my full script, the latest error log, and a screenshot of my app configuration for your reference.

Thank you for your time and assistance in resolving this critical issue.

Best regards,

Vijay

Hi @VIJAY_1675918 Could you please confirm if you are using the latest SDK version and passing sandbox access token as below?

configuration = upstox_client.Configuration(sandbox=True)
configuration.access_token = 'SANDBOX_ACCESS_TOKEN'

Please refer example for Sandbox mode

Thanks

Dear Upstox Support Team,

Thank you for your prompt response and for the suggestion regarding the Sandbox configuration.

Following your guidance, I have updated my Python script’s authentication logic to use the recommended configuration.sandbox = True flag.

I have also taken the following steps to ensure my setup is correct:

  1. I have updated my script to use the latest version of the upstox-python-sdk.

  2. I have regenerated a brand new, fresh access_token from the Sandbox console immediately before running the script to ensure it is valid and has not expired.

  3. I have meticulously verified that the api_key and api_secret in my script’s configuration exactly match the credentials for my Sandbox App in the developer console.

Unfortunately, despite implementing your suggested fix and taking these precautionary steps, the issue persists. The script successfully connects and configures the client, but the very first place_order call is still being rejected with the exact same error.

Error Code: UDAPI100050
Error Message: “Invalid token used to access API”

This is happening during live market hours.

For your reference, here is the new, corrected login_and_get_client function in my script, which now uses the official sandbox=True flag:

codePython

def login_and_get_client():
    """Handles authentication for both LIVE and SANDBOX environments."""
    global upstox_api_client
    
    configuration = upstox_client.Configuration()
    
    if ENVIRONMENT == "SANDBOX":
        logging.info("--- Connecting to SANDBOX Environment ---")
        # Using the official sandbox flag as per your recommendation
        configuration.sandbox = True
        configuration.access_token = SANDBOX_ACCESS_TOKEN
        try:
            api_client = upstox_client.ApiClient(configuration)
            logging.info("Successfully configured client for Sandbox using permanent token.")
            upstox_api_client = api_client
            return api_client
        except Exception as e:
            logging.error(f"Failed to configure Sandbox client. Error: {e}")
            return None
    
    else: # LIVE Environment
        # ... (Live login logic) ...

Given that:

  • The code is now using the officially recommended configuration.

  • The access_token is freshly generated and valid.

  • The api_key is correct.

…the persistent 401 Unauthorized error on the place_order endpoint strongly suggests a server-side issue, possibly related to the permissions or provisioning of my specific Sandbox account.

Could you please escalate this issue and have your technical team investigate the backend configuration for my Sandbox app to determine why it is rejecting orders placed with a valid token?

I have attached my full Python script, the complete log file from the latest failed attempt, and a screenshot of my Sandbox App configuration for your detailed analysis.

Thank you for your continued support in resolving this critical issue.

Best regards,

Vijay

Hi @VIJAY_1675918 , You should pass sandbox=True directly in the constructor as shown below — this will work:

configuration = upstox_client.Configuration(sandbox=True)

instead of setting it afterward like this

configuration = upstox_client.Configuration()
configuration.sandbox = True

Thanks

Dear Upstox API Support Team,

I hope this message finds you well.

I am writing to report a critical and persistent AttributeError I am encountering when using the official upstox-python-sdk (latest version) to fetch LTPs. The SDK appears to be missing the get_ltp method within the MarketQuoteApi class, despite this being a fundamental function.

Summary of the Issue:

When I instantiate the MarketQuoteApi and attempt to call the .get_ltp() method, the script immediately fails with the following error:
AttributeError: ‘MarketQuoteApi’ object has no attribute ‘get_ltp’

This occurs in both Live and Sandbox environments. I have confirmed that my authentication is successful before this call is made.

My Environment:

  • SDK: upstox-python-sdk (latest version, installed via pip install --upgrade)

  • Python Version: 3.9+

  • Operating System: Windows

Code Snippet Causing the Error:

The error originates from this standard function designed to fetch an LTP. The failure happens on the line marked ### ERROR HERE ###.

code Python

downloadcontent_copy

expand_less

    import upstox_client
from upstox_client.rest import ApiException

def get_ltp(client, instrument_key):
    """Fetches the Last Traded Price (LTP) for a given instrument."""
    if not client: 
        print("Error: Client object is not valid.")
        return None
        
    market_quote_api = upstox_client.MarketQuoteApi(client)
    
    try:
        # This is the line that fails with the AttributeError
        api_response = market_quote_api.get_ltp(instrument_key=instrument_key, api_version="v2") ### ERROR HERE ###
        
        if api_response.data and instrument_key in api_response.data:
            return api_response.data[instrument_key].last_price
        else:
            print(f"LTP data not found for {instrument_key} in API response.")
            return None
            
    except ApiException as e:
        print(f"API Error fetching LTP for {instrument_key}: {e}")
        return None
    except Exception as e:
        print(f"An unexpected error occurred in get_ltp for {instrument_key}: {e}")
        return None

# Example Usage:
# client = # Assume this is the successfully authenticated api_client object
# instrument_key = "NSE_EQ|INE002A01018" # Example for Reliance
# price = get_ltp(client, instrument_key)
  

My Specific Questions:

  1. Could you please confirm if the get_ltp method is indeed the correct function to use for fetching LTPs within the MarketQuoteApi class in the latest Python SDK?

  2. If it is not, could you provide the correct, definitive function name and its required arguments?

  3. If get_ltp is the correct function, could this AttributeError indicate an issue with the installed version of the upstox-client library itself, or a potential bug in the SDK?

This issue is a critical blocker for my application’s development. Any guidance or a working code sample for fetching an LTP would be immensely appreciated.

Thank you for your time and assistance.

Best regards,

Vijay