1

This is my 1st Python program. I am not a programmer. But have knowledge of VBA & html. Just started learning python. Q: In option chain analysis this code is trying to pull data from NSE site and should write in file "oidata.json". Code is getting executed without any error, but it is not writing anything in "oidata.json" file.

import requests
import json


url = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY"
headers= {'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36',
"accept-language":"en-US,en;q=0.9","accept-encoding":"gzip, deflate"}

def fetch_oi():
    r=requests.get(url,headers=headers).json()
    print(r)

    with open("oidata.json","w") as files:
       files.write(json.dumps(r, indent=4, sort_keys = True))


def main():
    fetch_oi()


if __name__ == ' __main__ ':
    main()
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74

1 Answers1

0

Try adding raise_for_status() after fetching the data. My bet is on malformed server response...

response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()

The Quickstart guide recommends the same.

It should be noted that the success of the call to r.json() does not indicate the success of the response. Some servers may return a JSON object in a failed response (e.g. error details with HTTP 500). Such JSON will be decoded and returned. To check that a request is successful, use r.raise_for_status() or check r.status_code is what you expect.

bobah
  • 18,364
  • 2
  • 37
  • 70