Scott Scott - 2 months ago 27
Python Question

Reading mashabe API using urllib

I have this code to read Mashape.com API in python 2. how can i read it in python 3?

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)


i tried this code but it had following error :

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)


error :

TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

Answer

In this line:

request = urllib.request.Request(URL, urllib.parse.urlencode(params), headers)

Try to replace to

data = urllib.parse.urlencode(params).encode('utf-8')
request = urllib.request.Request(URL, data, headers)
Comments