0

I made this simple script to test this API:

import requests
res = requests.get("https://icanhazdadjoke.com/")
print(res.json())

but I get the error:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print(res.json())
  File "/usr/lib/python3/dist-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 525, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I tested the API with curl -H "Accept: application/json" https://icanhazdadjoke.com/ and it returns OK:

{"id":"JeF69xAQSnb","joke":"A red and a blue ship have just collided in the Caribbean. Apparently the survivors are marooned.","status":200}

I also tested with other APIs and I always seem to get this error. I'm trying to learn about how to use APIs, so I'm kind of lost.

Daniel Oscar
  • 287
  • 1
  • 9
  • Your curl command sets the correct header and the Python doesn't. Print `res.text()` and you'll see it's returning the HTML you'd see if you navigated your browser to the URL. – ggorlen Mar 03 '21 at 00:18
  • Does this answer your question? [Using headers with the Python requests library's get method](https://stackoverflow.com/questions/6260457/using-headers-with-the-python-requests-librarys-get-method). Specifically, use `requests.get(url, headers={"accept": "application/json"})` – ggorlen Mar 03 '21 at 00:20
  • @ggorlen oh, that "-H" is for headers! I didn't know! – Daniel Oscar Mar 03 '21 at 00:24

0 Answers0