Search code examples
pythonresthp-alm

HP ALM Python rest api - How to properly pass cookie for API calls


How to pass the HP ALM authentication session object for rest api calls. I am following some examples to connect to HP ALM via REST API to run basic CRUD operations.

One of the example - https://github.com/vkosuri/py-hpalm/blob/master/hpalm/hpalm.py

Below is the code snippet to establish the connection which is working perfectly fine. I am getting 200 OK response for login.

headers = {'Cookie' : lwssocookie}
headers["Accept"] = 'application/xml'
login_url = self.base_url + '/qcbin/authentication-point/authenticate'

resp = requests.get(login_url, headers=headers, auth=HTTPBasicAuth(self.username, self.password), verify=self.verify)
alm_session = resp.headers['Set-Cookie']
logger.debug("Is QC session launched: %s" %alm_session)
cookie = ";".join((lwssocookie, alm_session))

But all the subsequent operations are failing with unauthorized error even though I added the cookies to header

self.headers['cookie'] = cookie
url = self.base_url + '/qcbin/rest/domains/' + self.domain + '/projects/' + self.project + '/test-instances'
response = requests.get(url, params=params, headers=self.getheaders())

Can anyone please suggest how to hold the session to run operations and what am I missing here.

I also tried to pass cookies in get call as below and even that didn't work.

response = requests.get(url, params=params, headers=self.getheaders(), cookies=cookie)

Thank you in advance


Solution

  • Thanks to requests.Session(), there is no need to manipulate HTTP headers for cookies.

    Here is a code snippet I run for old ALM version 12.01 which took me a couple of hours to design thanks to this post:

    session = requests.Session()
    session.verify = False
    
    auth = session.post(hpqc_server + "authentication-point/authenticate?login-form-required=y",
                        auth=HTTPBasicAuth(username, password))
    print("Authentication ", auth, auth.text, session.cookies)
    
    site_session = session.post(hpqc_server + "rest/site-session")
    print("Session ", site_session, site_session.text, session.cookies)
    
    check = session.get(hpqc_server + "rest/is-authenticated")
    print("Check ", check, check.text)
    
    # Enforce JSON output
    session.headers.update({ 'Accept': 'application/json' })
    projects = session.get(hpqc_server + "rest/domains/DOMAIN/projects")