I'm trying to use the Twitch API in a Django [python] web application. I want to send a request and get information back, but I don't really know what I'm doing.
curl -H 'Accept: application/vnd.twitchtv.v2+json' -X GET \
https://api.twitch.tv/kraken/streams/test_channel
How do I convert this python?
Thanks
Using the builtin urllib2:
>>> import urllib2
>>> req = urllib2.Request('https://api.twitch.tv/kraken/streams/test_channel')
>>> req.add_header('Accept', 'application/vnd.twitchtv.v2+json')
>>> resp = urllib2.urlopen(req)
>>> content = resp.read()
If you're using Python 3.x, the module is called urllib.request, but otherwise you can do everything the same.
You could also use a third-party library for HTTP, like requests, which has a simpler API:
>>> import requests
>>> r = requests.get('https://api.twitch.tv/kraken/streams/test_channel',
headers={'Accept': 'application/vnd.twitchtv.v2+json'})
>>> print(r.status_code)
422 # <- on my machine, YMMV
>>> print(r.text)
{"status":422,"message":"Channel 'test_channel' is not available on Twitch",
"error":"Unprocessable Entity"}
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