Reputation: 123
I am trying to fetch data from an API using Requests
in python.
Sometimes it works fine and sometimes it throws this error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I can't figure out what's the problem here, can anyone help me out.
Here's the API
Here is my code:
import requests
import json
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'symbol':'NIFTY'}
r = requests.get('https://www.nseindia.com/api/option-chain-indices', params = payload, headers = headers).json()
print(r.keys())
print(r['records'])
Upvotes: 0
Views: 381
Reputation: 2647
Because you need to set cookies to make this website work.
To do so with requests
, you need to use a session
.
import requests
s = requests.session()
headers = {'User-Agent': 'Mozilla/5.0'}
s.get("https://www.nseindia.com", headers=headers) # set cookies
payload = {'symbol':'NIFTY'}
r = s.get('https://www.nseindia.com/api/option-chain-indices', params=payload, headers=headers)
r.json() # will display content
Upvotes: 1