Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Requests get returns response code 401 for nse india website [closed]

I use this program to get the json data from https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY but since this morning it's not working as it returns <Response [401]>. The link loads fine on chrome though. Is there any way to fix this without using selenium ?

import json
import requests

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                         'like Gecko) '
                         'Chrome/80.0.3987.149 Safari/537.36',
           'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}

res = requests.get("https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY", headers=headers)
print(res)

like image 317
VarunS2002 Avatar asked Aug 23 '26 07:08

VarunS2002


2 Answers

Try this:

import requests

baseurl = "https://www.nseindia.com/"
url = f"https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                         'like Gecko) '
                         'Chrome/80.0.3987.149 Safari/537.36',
           'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}
session = requests.Session()
request = session.get(baseurl, headers=headers, timeout=5)
cookies = dict(request.cookies)
response = session.get(url, headers=headers, timeout=5, cookies=cookies)
print(response.json())

To access the NSE (api's) site multiple times then set cookies in each subsequent requests:

response = session.get(url, headers=headers, timeout=5, cookies=cookies)

like image 64
VarunS2002 Avatar answered Aug 25 '26 21:08

VarunS2002


To resolve the 401 Unauthorized error when fetching JSON data from https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY, use a requests.Session() to maintain session state and handle cookies. First, make a request to the base URL to establish the session, then request the data using the same session. Here's the code:

import requests

base_url = "https://www.nseindia.com/"
url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
    'Accept-Language': 'en,gu;q=0.9,hi;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br'
}

with requests.Session() as session:
    session.get(base_url, headers=headers)  # Establish session
    response = session.get(url, headers=headers)  # Fetch data
    if response.ok:
        data = response.json()
        print(data)
    else:
        print(f"Error: {response.status_code}")
like image 24
manan5439 Avatar answered Aug 25 '26 19:08

manan5439