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)
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)
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}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With