Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add basic authentication to a Python REST request?

I have the following simple Python code that makes a simple post request to a REST service -

params= { "param1" : param1,
          "param2" : param2,
          "param3" : param3 }
xmlResults = urllib.urlopen(MY_APP_PATH, urllib.urlencode(params)).read()
results = MyResponseParser.parse(xmlResults)

The problem is that the url used to call the REST service will now require basic authentication (username and password). How can I incorporate a username and password / basic authentication into this code, as simply as possible?

like image 283
froadie Avatar asked Sep 13 '10 16:09

froadie


People also ask

How do you add basic auth requests in python?

To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server. Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.

How do I authenticate API requests in python?

There are a few common authentication methods for REST APIs that can be handled with Python Requests. The simplest way is to pass your username and password to the appropriate endpoint as HTTP Basic Auth; this is equivalent to typing your username and password into a website.

How do you pass basic auth in header in Python?

You'll need to import the following first. Part of the basic authentication header consists of the username and password encoded as Base64. In the HTTP header you will see this line Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= . The encoded string changes depending on your username and password.


1 Answers

If basic authentication = HTTP authentication, use this:

import urllib
import urllib2

username = 'foo'
password = 'bar'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, MY_APP_PATH, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

params= { "param1" : param1,
          "param2" : param2,
          "param3" : param3 }

xmlResults = urllib2.urlopen(MY_APP_PATH, urllib.urlencode(params)).read()
results = MyResponseParser.parse(xmlResults)

If not, use mechanize or cookielib to make an additional request for logging in. But if the service you access has an XML API, this API surely includes auth too.

2016 edit: By all means, use the requests library! It provides all of the above in a single call.

like image 170
leoluk Avatar answered Oct 02 '22 14:10

leoluk