代码片段
这些示例展示了如何使用客户端凭据流从 Python 调用 RealityConnect API。每个片段都是自包含的:将其复制到 .py 文件中,设置你的凭据和资源 ID,然后使用 python your_script.py 运行它。
下面的每个片段都从此代码块开始。它使用客户端凭据进行身份验证,解析你的区域 API URL,并定义精简的 HTTP 辅助函数。
import base64import jsonimport mathimport os
import requests
CLIENT_ID = "your-client-id"CLIENT_SECRET = "your-client-secret"CLOUD_API_BASE = "https://cloud-api.prevu3d.com"
credentials = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()token_response = requests.post( f"{CLOUD_API_BASE}/oauth/token", data={"grant_type": "client_credentials"}, headers={"Authorization": f"Basic {credentials}"},)token_response.raise_for_status()access_token = token_response.json()["access_token"]
api_info_response = requests.get( f"{CLOUD_API_BASE}/oauth/api-info", headers={"Authorization": f"Bearer {access_token}"},)api_info_response.raise_for_status()api_info = api_info_response.json()
API_URL = api_info["apiUrl"].rstrip("/")ORGANIZATION_ID = api_info["organization"]["id"]HEADERS = {"Authorization": f"Bearer {access_token}"}
def api_get(path: str, params: dict | None = None) -> dict: response = requests.get(f"{API_URL}{path}", headers=HEADERS, params=params) response.raise_for_status() return response.json()
def api_post(path: str, body: dict) -> dict | None: response = requests.post(f"{API_URL}{path}", json=body, headers=HEADERS) response.raise_for_status() if response.status_code == 204: return None return response.json()
def api_patch(path: str, body: dict) -> dict: response = requests.patch(f"{API_URL}{path}", json=body, headers=HEADERS) response.raise_for_status() return response.json()
def api_delete(path: str) -> None: response = requests.delete(f"{API_URL}{path}", headers=HEADERS) response.raise_for_status()