Search code examples
pythonhttpsget-request

Send a HTTP Request in Python - urllib2.HTTPError: HTTP Error 401: Unauthorized


I am trying to write a python script to send a HTTP request. I read from the Python documentation on urllib2 library (https://docs.python.org/2/howto/urllib2.html#id6) and took the sample code with authentication, but I still get errors.

Here's my code (* top_level_url = login url, a_url = api request, which works on the web, and shows the response):

import urllib2

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
user='MY_USER_NAME'
passwd='MY_PASSWORD'
top_level_url = "https://next.adjust.com/#/login"
password_mgr.add_password(None, top_level_url, user, passwd)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# use the opener to fetch a URL
a_url = 'https://api.adjust.com/kpis/v1/vzpmna78ud8m/cohorts?start_date=2016-12-05&end_date=2016-12-06&kpis=sessions&grouping=os_names,countries'
opener.open(a_url)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)

But when I run the code, I get an error:

Traceback (most recent call last):
  File "httptest3.py", line 19, in <module>
    opener.open(a_url)
  File "/usr/lib64/python2.7/urllib2.py", line 437, in open
    response = meth(req, response)
  File "/usr/lib64/python2.7/urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib64/python2.7/urllib2.py", line 475, in error
    return self._call_chain(*args)
  File "/usr/lib64/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/lib64/python2.7/urllib2.py", line 558, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
 urllib2.HTTPError: HTTP Error 401: Unauthorized

I've tried multiple solution to this error, but I keep getting the same one.

Does anyone knows whats wrong in my code? Or do you have another code sample that works?


Solution

  • It looks like you adjust.com uses another kind of authentication for their api than u are using.

    U should read this documentation: https://docs.adjust.com/en/kpi-service/#authentication

    Instead of using a username and password, you should add this http header to you request:

    Authorization: Token token=your_user_token

    Or you can add &user_token=your_user_token to your api call.