python script to access tfs rest api

I was working in a project where I have to access Team Foundation Server (TFS) Rest API in Python script. It was little bit tricky job to access TFS REST API from python 2 . Specially for beginners like me 🙂 . I was facing issue to authenticate TFS REST API from python script whereas same credentials is working in Web Browser. I had debug this issue at least 4 hours. during debugging I have gone through the Request and Response headers of the REST API in Web Browser,  then I found one clue. TFS uses NTLM authentication protocols. This helps me to solve the issue. Now I have started looking the Python Library which does the NTLM authentication and got the success in very short time. Python has requests_ntlm library that allows for HTTP NTLM authentication. I am sharing my working code.

import requests
from requests_ntlm import HttpNtlmAuth

username = '\\'
password = ''
tfsApi = 'https://{myserver:8080}/tfs/collectionName/_apis/projects?api-version=2.0'

response = requests.get(tfsApi,auth=HttpNtlmAuth(username,password))
if(tfsResponse.ok):
    tfsResponse = tfsResponse.json()
    print(tfsResponse)
else:
    tfsResponse.raise_for_status()

I was getting below Authentication Error with request library:

Traceback (most recent call last):
File "D:\Scripts\tfs.py", line 13, in
tfsResponse.raise_for_status()
File "C:\Python27\lib\site-packages\requests\models.py", line 862, in raise_fo
r_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://{myserver}/tfs/collectionName/_apis/projects?api-version=2.0

Source:
https://msdn.microsoft.com/en-us/library/aa833874(v=vs.110).aspx
https://pypi.python.org/pypi/requests_ntlm/

(Visited 3,246 times, 79 visits today)