IdeoREX
IdeoREX

Reputation: 1485

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

Upvotes: 2

Views: 4883

Answers (2)

miku
miku

Reputation: 188024

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"}

Upvotes: 7

Brendan
Brendan

Reputation: 163

I usually use urllib2 for my api requests in (blocking) python apps.

>>> import urllib2
>>> req = urllib2.Request('https://api.twitch.tv/kraken/streams/test_channel', None, {'Accept':'application/vnd.twitchtv.vs+json'})
>>> response = urllib2.urlopen(req)

You can then access the text returned with response.read(). From there you can parse the JSON with your preferred library, though I generally just use json.loads(response.read()).

I would keep in mind, though, that this is for 2.7, if you are using python 3 the libraries have been moved around and this can be found in urllib.request

Upvotes: 2

Related Questions