Python SDK
Listings API 官方 Python 用戶端,提供型別化資源、游標分頁、自動重試及具名錯誤。
listingsapi 套件是 Listings API 的官方 Python 用戶端。它以具備型別定義的資源類別封裝 REST 層,支援以游標為基礎的分頁、暫時性錯誤的自動重試,並為每種失敗情況提供具名例外,包括平台以 HTTP 200 傳回錯誤酬載的情況。
安裝
pip install listingsapi需要 Python 3.9 或更新版本。唯一的執行階段相依套件是 requests。
驗證身分
import listingsapi # Reads LISTINGSAPI_KEY from the environment automaticallyclient = listingsapi.ListingsAPI() # Or pass the key explicitlyclient = listingsapi.ListingsAPI(api_key="your-api-key")從 Listings API 開發者儀表板的 API 金鑰 → 新增金鑰取得您的 API 金鑰。
用戶端接受 3 個選用的關鍵字引數:
詳情請參閱設定。
簡易範例
import listingsapi client = listingsapi.ListingsAPI() page = client.locations.list(first=5)for loc in page: print(loc.name, loc.city) print(f"has_more: {page.has_more}")資源
每個資源都是用戶端的屬性:
用戶端本身提供 4 個輔助方法:
client.plan_sites() # directories included in your planclient.subcategories() # business categories (IDs for locations.add)client.countries() # supported countries and states (ISO codes)client.subscriptions() # active subscriptions for the account分頁
傳回清單的方法使用以游標為基礎的分頁。每個支援分頁的方法都會傳回可迭代的 SyncPage,並提供 .has_more、.next_page()、.auto_paging_iter() 和 .total。
# Fetch one pagepage = client.locations.list(first=25)for loc in page: print(loc.name) # Check if more pages existif page.has_more: next_page = page.next_page() # Auto-paginate through every resultfor loc in client.locations.list(first=100).auto_paging_iter(): print(loc.name)回應物件
所有方法都會傳回 APIObject(支援屬性和 dict 存取)或 SyncPage(可迭代且支援分頁)。APIObject 也支援 .get() 和 .to_dict()。
loc = client.locations.retrieve(16808) # Attribute accessprint(loc.name)print(loc.city) # Dict-style accessprint(loc["stateIso"]) # Safe access with a defaultprint(loc.get("website", "no website")) # Raw dictdata = loc.to_dict()錯誤處理
所有 SDK 錯誤都衍生自 listingsapi.ListingsAPIError。API 失敗時會引發 APIError 或其子類別之一:AuthenticationError、PermissionDeniedError、NotFoundError、ValidationError、RateLimitError(附帶 .retry_after)和 InternalServerError。網路失敗時會引發 APIConnectionError。
APIError 包含 status_code、code(第 1 個平台錯誤碼,e.g。SY10005)、errors(每個項目都正規化為 {"code", "message", "context"} dict)和 response_body。
平台會在 HTTP 200 回應主體中回報某些失敗情況:頂層的 errors[] 酬載(無效的權杖會以 SY90005 傳回),以及含有 success=false 的寫入回應。SDK 也會針對這些情況引發例外,因此您完全不需要自行檢查 success 旗標。
import listingsapi client = listingsapi.ListingsAPI() try: client.locations.retrieve(999999)except listingsapi.NotFoundError: print("No such location")except listingsapi.RateLimitError as e: print(f"Rate limited, retry in {e.retry_after}s")except listingsapi.APIError as e: print(e.status_code, e.code) for err in e.errors: print(err["code"], err["message"])完整的例外階層請參閱錯誤處理。