使用Purview REST API查询资产无结果的问题求助
问题描述
使用Python调用Purview API时,请求返回状态码200,但无法查询到任何数据资产,而Purview账户中实际存在资产。
调用代码
import requests import json # Variables endpoint = "https://gp-purview-account.purview.azure.com/datamap/api/search/query?api-version=2023-09-01" api_version = "2023-09-01" url = f"{endpoint}/datamap/api/search/query?api-version={api_version}" token = token #replaced actual token with 'token' headers = { "Content-Type": "application/json", "Authorization": f"Bearer {token}" } body = { "keywords": "*" } # Make the POST request response = requests.post(url, headers=headers, json=body) # Check the response status and print the result if response.status_code == 200: print("Request was successful.") print(response.json()) # Print the response JSON assets = response.json().get('entities', []) if assets: for asset in assets: print(f"Name: {asset['attributes']['name']}, Type: {asset['typeName']}, GUID: {asset['guid']}") else: print("No assets found.") else: print(f"Request failed with status code {response.status_code}") print(response.text)
响应内容
Request was successful.
{'@search.count': 0, 'value': [], '@search.facets': None}
No assets found.
已知条件:Token有效且为最新,应用注册已配置“User Impersonation”委托权限。
排查与解决步骤
1. 修正URL拼接错误
代码中endpoint已包含完整的查询路径和api-version,后续再次拼接导致URL重复(变成https://gp-purview-account.purview.azure.com/datamap/api/search/query?api-version=2023-09-01/datamap/api/search/query?api-version=2023-09-01),这会导致API解析异常,虽返回200但实际是无效请求。
修正后的URL构建代码:endpoint = "https://gp-purview-account.purview.azure.com" api_version = "2023-09-01" url = f"{endpoint}/datamap/api/search/query?api-version={api_version}"2. 修正响应数据解析逻辑
Purview搜索API的资产数据存储在value字段而非entities,原代码用entities字段获取数据自然返回空。
修正后的解析代码:if response.status_code == 200: print("Request was successful.") response_data = response.json() print(response_data) assets = response_data.get('value', []) if assets: for asset in assets: print(f"Name: {asset['attributes']['name']}, Type: {asset['typeName']}, GUID: {asset['guid']}") else: print("No assets found.")3. 验证Purview权限分配
除了应用注册的委托权限,需确认该应用在Purview账户的**访问控制(IAM)**中被分配了「数据读取者」或更高权限,否则即使Token有效也无法读取资产数据。4. 优化搜索关键词(可选)
若修正后仍无结果,可尝试更具体的搜索条件,比如指定资产类型:body = { "keywords": "typeName:AzureBlobStorage" }
内容的提问来源于stack exchange,提问作者John H

