Reputation: 1
Using python to send json requests to a rest api. The initial request is to login! The login, when successful, returns a key to be used with every subsequent request. Login server is down at this very moment, so I've modified my code just as an example to show the issue I face.
#!/usr/bin/env python
import requests
from requests.auth import HTTPDigestAuth
import json
r = requests.get('myApi')
data = json.loads(r.content)
print(r.status_code)
for key, value in data.items():
print key
print value
apikey = data['startRow']
The output is;
401
response
{u'status': 401, u'startRow': 0, u'totalRows': 1, u'data': {u'errors': [u'Credentials are not valid']}, u'endRow': 1}
Traceback (most recent call last):
File "zzzz\test.py", line 24, in <module>
apikey = data['startRow']
KeyError: 'startRow'
How can a specific param in the dict be referenced? It appears as though the value is actually the whole response itself is the value, and not startRow or errors, etc.
Upvotes: 0
Views: 1009
Reputation: 6302
Use the convenient requests.Response.json()
to let requests
take care of parsing the JSON response:
import requests
r = requests.get('myApi')
data = r.json()
apikey = data['startRow']
Upvotes: 0