API 使用 python 调用 Azure DevOps 以获取组织中的用户列表

API call using python to Azure DevOps to get list of users in an organization

我正在尝试使用 Python 对 Azure DevOps 进行简单的 api 调用以获取用户列表。 URL 正在通过浏览器提供结果,但在编写如下脚本时出现错误。我需要进一步处理 json 响应。有人可以帮忙吗? Python版本:3.8.3

脚本

import requests
import json
response = requests.get('https://vssps.dev.azure.com/siva*****/_apis/graph/users')
print(response)
print(response.json())

**Output:**
<Response [203]>
Traceback (most recent call last):
  File "c:/Users/HP/OneDrive/Documents/github/terraform/azure-aks-kubernetes-masterclass/25-Azure-DevOps-Terraform-Azure-AKS/test.py", line 5, in <module>
    print(response.json())
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 900, in json      
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)

当您 运行 其余 API 时,203 错误是身份验证错误。

您可以使用 PAT(Personal Access Token) 作为身份验证方法。

您可以授予 PAT Graph Read 范围。

这是 Python 示例:

import requests
import base64

pat = 'PAT'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')

headers = {
    'Accept': 'application/json',
    'Authorization': 'Basic '+authorization
}

response = requests.get(
    url="https://vssps.dev.azure.com/{Organization}/_apis/graph/users?api-version=6.0-preview.1", headers=headers)
print(response)