title: urllib & python3: HTTP Error 405: Method Not Allowed
body: <p>I am trying to do a simple authentication using Python3 and urllib on an API that should return account balances.</p>
  
  <p>The code I have is the following:</p>
  
  <pre><code>import urllib
  import urllib.request
  import json
  
  id = "nkkhuz6" # fake
  secret = "s9MeR0J9yxtndLBPVA" # fake
  auth_str = id + ":" + secret
  
  def getBalances():
  
      values = {'u' : auth_str}
      data = urllib.parse.urlencode(values)
      data = data.encode('utf-8') # data should be bytes
  
      request = urllib.request.Request(url = "https://api.com", data = data)
  
      with urllib.request.urlopen(request) as f:
          print(json.loads(f.read().decode('utf-8')))
  </code></pre>
  
  <p>However when I run <code>getBalances()</code> I get the following errors:</p>
  
  <pre><code>Adriaans-MacBook-Pro:Documents adriaanjoubert$ python3 main.py
  Traceback (most recent call last):
    File "main.py", line 96, in &lt;module&gt;
      getBalances()
    File "main.py", line 19, in getBalances
      with urllib.request.urlopen(request) as f:
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 161, in urlopen
      return opener.open(url, data, timeout)
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 469, in open
      response = meth(req, response)
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 579, in http_response
      'http', request, response, code, msg, hdrs)
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 507, in error
      return self._call_chain(*args)
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441, in _call_chain
      result = func(*args)
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 587, in http_error_default
      raise HTTPError(req.full_url, code, msg, hdrs, fp)
  urllib.error.HTTPError: HTTP Error 405: Method Not Allowed
  </code></pre>
  
  <p>I am sure the URL is correct and if I append a trailing <code>/</code> I get the error <code>urllib.error.HTTPError: HTTP Error 404: Not Found</code></p>
  
  <p>When I run the following code I do get my account balances:</p>
  
  <pre><code>cmd = """curl -u """ + auth_str + """ https://api.com/"""
  os.system(cmd)
  </code></pre>
  
  <p>What am I doing wrong? I would like to use <code>urllib</code> so that I can store the stuff I get back from the API in a variable.</p>