Search code examples
pythonresturllib2

REST GET request on Python sending named argument


I am playing from Linux using curl inside bash but now I need to move my script to python in order to be more effective. What is the best way to do something like the following line on python?

curl baseuri:port/resource -u user:pswd

I played already with urllib2 but I dont get a clue on how to send the "-u user:pswd"


Solution

  • You'll need to use a HTTPPasswordMgrWithDefaultRealm instance to handle the authentication, and add in a HTTPBasicAuthHandler handler to respond to the authentication challenge:

    import urllib2
    
    url = 'baseuri:port/resource'
    username = 'user'
    password = 'pswd'
    
    pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    pwmgr.add_password(None, url, username, password)    
    authhandler = urllib2.HTTPBasicAuthHandler(passman)
    
    opener = urllib2.build_opener(authhandler)
    response = opener.open(theurl)
    

    Yes, this is a handful.

    If you can install a 3rd party library, then add use the requests library; it'll be so much easier:

    import requests
    
    url = 'baseuri:port/resource'
    username = 'user'
    password = 'pswd'
    
    response = requests.get(url, auth=(username, password))