使用令牌获得VSTS API的授权,但status.code = 203

时间:2018-07-02 06:53:37

标签: python http-headers azure-devops token azure-devops-rest-api

我正在尝试使用VSTS 5.0的API,但是当我尝试将Token与python一起使用时得到203。

headers = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
    'X-Requested-With':'XMLHttpRequest',
    'Authorization': b'Basic '+ base64.b64encode(personal_access_token.encode('utf-8')),
    'content-type': 'application/json',}

def get_page_list():
    url = 'https://{account}.visualstudio.com/DefaultCollection/_apis/projects'
    try:
        response = requests.get(url, headers=headers, verify = False)
        print (response.status_code)
        if response.status_code == 200:
            return response.json()
    except requests.ConnectionError as e:
        print('Error*****', e.args)

if __name__ == '__main__':
    json = get_page_list()
    print(json)

这将返回至此:203无

我真的不明白是怎么回事。

2 个答案:

答案 0 :(得分:0)

确保您的PAT有效,并且您使用的api版本应为4.0。在这种情况下,您也可以尝试以下代码段:Authenticating to VisualStudioOnline REST API with Personal Access Token using Python 3.6

import json
import base64
import urllib.request

personal_access_token = ":xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

headers = {}
headers['Content-type'] = "application/json"
headers['Authorization'] = b'Basic ' + 
base64.b64encode(personal_access_token.encode('utf-8'))

instance = "mycompany.visualstudio.com"
project = "MyProject"
repository ="MyRepository"
pullrequest = "3468"
api_version = "3.0"

repositories_url = ("https://%s/DefaultCollection/%s/_apis/projects?
api-version=%s" % (instance, project, api_version))
print(repositories_url)

request = urllib.request.Request(repositories_url, headers=headers)
opener = urllib.request.build_opener()
response = opener.open(request)
print(response.read())

答案 1 :(得分:0)

最后,我们找到了获取授权的方法:

    try:
    response = requests.get(url1, headers=headers, verify = False,auth = (MyToken,''))
    if response.status_code == 200:
        return response.json()
except requests.ConnectionError as e:
    print('Error', e.args)

谢谢