-2

I am getting error for print statement 'Request' object has no attribute 'getcode' and read

sample = '[{{ "t": "{0}", "to": "{1}", "evs": "{2}", "fds": {3} }}]'

response = urllib.request.Request(REST_API_URL, sample.encode('utf-8'))

print("Response: HTTP {0} {1}\n".format(response.getcode(), response.read()))
steveJ
  • 2,171
  • 3
  • 11
  • 16

2 Answers2

2

urllib.request.Request is the class that the urllib.request module uses to abstract a request. To make an HTTP request you should use urllib.request.urlopen instead:

response = urllib.request.urlopen(REST_API_URL, sample.encode('utf-8'))
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

the variable you named response is actually an instance of a urllib.request.Request. if you want a response you need to send the request first, and that is done using urllib.request.urlopen().

BUT instead of figuring out how to use python urllib.request, I suggest you to try the requests module which is MUCH easier to use. For example you code can be expressed like so:

import requests
resp = requests.post(REST_API_URL, json=[{{ "t": "{0}", "to": "{1}", "evs": "{2}", "fds": {3} }}])
print("Response: HTTP {} {}".format(resp.statuscode, resp.content)
Guillaume
  • 5,497
  • 3
  • 24
  • 42