Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl to Python Conversion

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

like image 918
IdeoREX Avatar asked Jul 19 '26 07:07

IdeoREX


1 Answers

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"}
like image 88
miku Avatar answered Jul 20 '26 21:07

miku