Not able to fetch historical data

Hii, iam trying to fetch historical data for nifty, with below url

https://api.upstox.com/v2/historical-candle/NSE_INDEX|Nifty%2050/day/2025-02-11/2025-02-11

https://api.upstox.com/v2/historical-candle/NSE_INDEX|Nifty 50/day/2025-02-11/2025-02-11

getting response as follows for both url

Full API Response for 2025-02-11: {‘status’: ‘success’, ‘data’: {‘candles’: }}
No data found for NSE_INDEX|Nifty 50 on 2025-02-11

kindly assist me

Hi @tnnageshwar,

Welcome to the Upstox Community!

We are checking this and will get back to you soon. Thanks for your patience.

Hi @tnnageshwar, I am receiving the correct response today for the specified URL. Since this is a historical API, there would have been no data if you tried it yesterday.

{
  "status": "success",
  "data": {
    "candles": [
      [
        "2025-02-11T00:00:00+05:30",
        23383.55, 23390.05, 22986.65, 23071.8, 0, 0]
    ]
  }
}

import requests
import time
import json # Ensure JSON module is used
import brotli # To handle Brotli compressed responses

ACCESS_TOKEN = “your_access_token”

headers = {
“Accept”: “application/json”,
“Authorization”: f"Bearer {ACCESS_TOKEN}",
“User-Agent”: “PostmanRuntime/7.30.0”,
“Cache-Control”: “no-store, no-cache, must-revalidate, max-age=0”,
“Pragma”: “no-cache”,
“Expires”: “0”,
“Connection”: “keep-alive”,
“Host”: “api.upstox.com”,
“Accept-Encoding”: “gzip, deflate, br”, # Supports Brotli (‘br’)
“Referer”: “https://www.postman.com”,
“vary”: “Origin, Access-Control-Request-Method, Access-Control-Request-Headers”,
“cdn-cache-control”: “public, max-age=70115”,
“x-content-type-options”: “nosniff”,
“x-xss-protection”: “1; mode=block”,
“strict-transport-security”: “max-age=0; includeSubDomains”,
“x-frame-options”: “DENY”,
“CF-Cache-Status”: “MISS”
}

def fetch_data(symbol, date_str):
unique_cache_bypass = str(int(time.time())) # Unique timestamp to avoid cache
url = f"https://api.upstox.com/v2/historical-candle/{symbol}/day/{date_str}/{date_str}?nocache={unique_cache_bypass}"

print(f"📡 Fetching data for {date_str}: {url}")

response = requests.get(url, headers=headers)

print(f"📜 Response Headers for {date_str}: {response.headers}")

# Get raw response content
raw_content = response.content
encoding = response.headers.get("Content-Encoding", "").lower()

# Debugging: Print first 100 bytes of the raw response
print(f"📩 Raw Response (First 100 Bytes): {raw_content[:100]}")

# Try Brotli decompression only if Content-Encoding is 'br'
if encoding == "br":
    try:
        raw_content = brotli.decompress(raw_content)  # Attempt Brotli decompression
    except brotli.error as e:
        print(f"❌ Brotli Decompression Error: {e}")
        print(f"⚠️ Falling back to raw JSON parsing...")

try:
    raw_text = raw_content.decode("utf-8", errors="ignore")
    data = json.loads(raw_text)  # ✅ FIXED: Using `json.loads()`

    print(f"📩 Full API Response for {date_str}: {data}")

    if "data" in data and "candles" in data["data"] and data["data"]["candles"]:
        print(f"✅ Data Found for {symbol} on {date_str}")
        print("OHLCV:", data["data"]["candles"][0])
    else:
        print(f"⚠️ No data found for {symbol} on {date_str}")
except json.JSONDecodeError as e:
    print(f"❌ JSON Parsing Error: {e}")
    print(f"⚠️ Raw response: {raw_text[:200]}")  # Show first 200 characters for debugging

Run for NIFTY on Feb 11

fetch_data(“NSE_INDEX|Nifty%2050”, “2025-02-11”)

for the above code, iam getting following response

envdr.rahultn@DrRahuls-MacBook-Air tokens % python3 test.py
:satellite: Fetching data for 2025-02-11: https://api.upstox.com/v2/historical-candle/NSE_INDEX|Nifty%2050/day/2025-02-11/2025-02-11?nocache=1739366161
:scroll: Response Headers for 2025-02-11: {‘Date’: ‘Wed, 12 Feb 2025 13:16:01 GMT’, ‘Content-Type’: ‘application/json’, ‘Transfer-Encoding’: ‘chunked’, ‘Connection’: ‘keep-alive’, ‘vary’: ‘Origin, Access-Control-Request-Method, Access-Control-Request-Headers’, ‘requestid’: ‘e82c8bea-ddef-40a3-a0bd-cc6baeea9086’, ‘cdn-cache-control’: ‘public, max-age=80097’, ‘x-content-type-options’: ‘nosniff’, ‘x-xss-protection’: ‘1; mode=block’, ‘Cache-Control’: ‘max-age=14400, must-revalidate’, ‘pragma’: ‘no-cache’, ‘expires’: ‘0’, ‘strict-transport-security’: ‘max-age=0; includeSubDomains’, ‘x-frame-options’: ‘DENY’, ‘Last-Modified’: ‘Tue, 11 Feb 2025 03:15:02 GMT’, ‘CF-Cache-Status’: ‘HIT’, ‘Age’: ‘65724’, ‘Set-Cookie’: ‘__cf_bm=X5daJcw2USWgRRAnVT5O59E6Xw4IQer3XJhqwBJtIyA-1739366161-1.0.1.1-.YW1DnEVN7pxoSsr6SRohuI4EYr49KuoA2EjG.nlj8Xsn5cEVug5zSPxYujykA7D; path=/; expires=Wed, 12-Feb-25 13:46:01 GMT; domain=.upstox.com; HttpOnly; Secure; SameSite=None, _cfuvid=sjpUUH9tmbayEEzxhTNM8ZJZSRpZPCH1O5lZI5eg7DE-1739366161315-0.0.1.1-604800000; path=/; domain=.upstox.com; HttpOnly; Secure; SameSite=None’, ‘Server’: ‘cloudflare’, ‘CF-RAY’: ‘910cd9cc181ba8f5-MAA’, ‘Content-Encoding’: ‘br’, ‘alt-svc’: ‘h3=“:443”; ma=86400’}
:envelope_with_arrow: Raw Response (First 100 Bytes): b’{“status”:“success”,“data”:{“candles”:}}’
:x: Brotli Decompression Error: BrotliDecompress failed
:warning: Falling back to raw JSON parsing…
:envelope_with_arrow: Full API Response for 2025-02-11: {‘status’: ‘success’, ‘data’: {‘candles’: }}
:warning: No data found for NSE_INDEX|Nifty%2050 on 2025-02-11
envdr.rahultn@DrRahuls-MacBook-Air tokens %

dont consider headers, i was usins postman there i was getting the output not from my code,
but still no output

kindly assist me

Hi @tnnageshwar,

We are checking this and will get back to you soon. Thanks.

if i want to fetch previous day close price, with minute candle, what is the url i need to give?
if today is 12feb, to fetch 11th feb 15:29:00 candle close price…

@tnnageshwar You need to use the Historical Candle API with a 1-minute interval.

Refer to the documentation here: Historical Candle Data API.