Reading mashabe API using urllib
<p>I have this code to read Mashape.com API in python 2. how can i read it in python 3?</p>

<p><strong>code</strong></p>

<pre><code>import urllib, urllib2, json
from pprint import pprint

URL = "https://getsentiment.p.mashape.com/"
text = "The food was great, but the service was slow."
params = {'text': text, 'domain': 'retail', 'terms': 1, 'categories': 1,'sentiment': 1, 'annotate': 1}
headers = {'X-Mashape-Key': YOUR_MASHAPE_KEY}

opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(URL, urllib.urlencode(params), headers=headers)
response = opener.open(request)
opener.close()

data = json.loads(response.read())
pprint(data)
</code></pre>

<p>i tried this code but it had following error :</p>

<pre><code>import urllib.parse
import urllib.request

URL = "https://getsentiment.p.mashape.com/"
text = "The food was great, but the service was slow."
params = {'text': text, 'domain': 'retail', 'terms': 1, 'categories': 1, 'sentiment': 1, 'annotate': 1}
headers = {'X-Mashape-Key': YOUR_MASHAPE_KEY}

opener = urllib.request.build_opener(urllib.request.HTTPHandler)
request = urllib.request.Request(URL, urllib.parse.urlencode(params), headers)
response = opener.open(request)
opener.close()

data = json.loads(response.read())
print(data)
</code></pre>

<p><strong>error :</strong></p>

<pre><code>TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
</code></pre>

<p>In this line:</p>

<pre><code>request = urllib.request.Request(URL, urllib.parse.urlencode(params), headers)
</code></pre>

<p>Try to replace to </p>

<pre><code>data = urllib.parse.urlencode(params).encode('utf-8')
request = urllib.request.Request(URL, data, headers)
</code></pre>

python python-3.x mashape