Search code examples
pythonrequestazure-devopsaccess-tokenazure-devops-rest-api

Using a personal access token for azure devops API repository manipulation


I have generated a personal access token from the Azure Devops user interface but am unable to use this to make requests against the Devops API.

I have tried many different header fields, but I am always redirected to the log in page as though I hadn't authenticated.

token = #Token generated on Devops project page
token_bytes = token.encode('utf-8')
token64 = base64.b64encode(token_bytes)
authorization_string = "basic " + str(token64)

repo_endpoint_url = "https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1".format(organization=organization, project=project)

headers = {"Content-Type" : "application/json", "Authorization" : authorization_string}

response = requests.get(repo_endpoint_url, headers)

response is always 203 with login page HTML. This is what I'd expect to see if I didn't have an access token in the header.

I have tried, "Bearer" instead of "basic", I have tried adding {username}:{token}, and many other little tweaks.

What am I doing wrong?


Solution

  • I just scrapbooked following code which worked for me:

    import requests
    import base64
    
    repo_endpoint_url = "https://dev.azure.com/<organization>/<project>/_apis/git/repositories?api-version=5.1"
    
    username = "" # This can be an arbitrary value or you can just let it empty
    password = "<your-password-here>"
    userpass = username + ":" + password
    b64 = base64.b64encode(userpass.encode()).decode()
    headers = {"Authorization" : "Basic %s" % b64} 
    
    response = requests.get(repo_endpoint_url, headers=headers)
    print(response.status_code) # Expect 200