Sentry API 使用筆記
Sentry API 使用筆記
本文為使用Sentry API的筆記, 并非搭建Sentry的筆記
官方文檔: ?https://docs.sentry.io/api/
官方社區(qū): ?https://forum.sentry.io/
官方提醒:(2017年5月) The current version of the web API is known as v0 and is considered to be in a draft phase. While we don’t expect public endpoints to change greatly, keep in mind that the API is still under development.
身份驗證
sentry API 的身份驗證參數(shù)通過請求頭傳遞,所有API都需要包含此請求頭。
requests.get(api_url, headers=header)
如果沒有提供此請求頭參數(shù)會返回錯誤提示: {"detail": "Authentication credentials were not provided."}
。
headers
具體寫法為:
{'Authorization': 'Bearer TOKEN'}
其中TOKEN在項目設(shè)置中的API -- Auth Tokens
里設(shè)置. 如果TOKEN錯誤會返回錯誤提示: {"detail": "Invalid token"}
API 列表
Sentry 的API分為幾類, 具體每個API的含義可以直接看官方文檔. 本文以Events
類別下的List a Project’s Events
舉例說明如何使用這些API.
官方說明如下:
GET?/api/0/projects/{organization_slug}/{project_slug}/events/ Return?a?list?of?events?bound?to?a?project. Note:?This?endpoint?is?experimental?and?may?be?removed?without?notice. Path?Parameters: organization_slug?(string)?–?the?slug?of?the?organization?the?groups?belong?to. project_slug?(string)?–?the?slug?of?the?project?the?groups?belong?to. Method: GET Path: /api/0/projects/{organization_slug}/{project_slug}/events/
即:
請求方式:get
請求地址:你的sentry地址/api/0/projects/{organization_slug}/{project_slug}/events/
其中organization_slug
是組織名, project_slug
是項目名。
注意:
+ 并非所有請求都是get方式,比如刪除相關(guān)API使用delete
,更新相關(guān)API使用put
。
+ 有些API還需要其他請求頭, 比如更新issue的API還需要Content-Type: application/json
處理返回結(jié)果
此處以List a Project’s Events?
API 為例。
如果參數(shù)都沒問題的話API會以字符串形式返回100個(如果有的話,不足100個則直接返回全部) events
組成的列表, 每個event
都是json
格式的。
直接使用json
模塊載入返回結(jié)果:
json.loads(response.text)
這樣會得到一個列表, 每項均是一個dict
, 每個dict
包含了一個event
的信息。
如果這個項目的event
不止100條, sentry還會返回下一頁的url。 沒錯, sentry把100條event
作為一頁請求返回給接口調(diào)用, 要獲得下一頁events
的話需要從返回結(jié)果的響應(yīng)頭 response.headers
中獲取下一頁請求地址。
官方說明如下:
HTTP/1.0?200?OK Date:?Sat,?14?Feb?2015?18:47:20?GMT Content-Type:?application/json Content-Language:?en Allow:?GET,?HEAD,?OPTIONS Link:; ??rel="previous";?results="false",; ??rel="next";?results="true"
其中Link
中就包含了我們需要的下一頁地址(示例中為https://sentry.io/api/0/projects/1/groups/?&cursor=1420837533:0:0`)
link = response.headers.get('Link')
接下來用正則或者其他什么方式從字符串里提取下一頁地址再請求即可, 一直到無法提取到下一頁地址或下一頁地址返回結(jié)果為空。