2

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.
6
  • Post the problem you are having with python 3, and why you cannot "read it" Commented Sep 13, 2016 at 15:28
  • i dont know how to read it , i copied this code from somewhere and i didnt found such a thing for python 3 Commented Sep 13, 2016 at 15:29
  • Yeah, but what happens when you run this code with python 3? Commented Sep 13, 2016 at 15:31
  • looks like urllib2 is changed in python 3 Commented Sep 13, 2016 at 15:33
  • What line is giving this error? Commented Sep 13, 2016 at 15:40

1 Answer 1

1

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)
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.