官網地址:https://developer.github.com/v3/
目錄
默認,所有請求都接收v3版本的API。我們推薦顯式地請求 -- 通過Accept header。
Accept: application/vnd.github.v3+json
所有API 的訪問都是通過HTTPS,且來自https://api.github.com。 所有數據都以JSON形式來發送和接收。
curl -i https://api.github.com/users/octocat/orgs HTTP/1.1 200 OK Server: nginx Date: Fri, 12 Oct 2012 23:33:14 GMT Content-Type: application/json; charset=utf-8 Connection: keep-alive Status: 200 OK ETag: "a00049ba79152d03380c34652f2cb612" X-GitHub-Media-Type: github.v3 X-RateLimit-Limit: 5000 X-RateLimit-Remaining: 4987 X-RateLimit-Reset: 1350085394 Content-Length: 5 Cache-Control: max-age=0, private, must-revalidate X-Content-Type-Options: nosniff
blank fields(空字段)都是作為null,而非被忽略。
所有的時間戳都以ISO 8601格式返回。
YYYY-MM-DDTHH:MM:SSZ
summary representations 概要描述
當你獲取一個資源列表時,響應會包含該資源的attributes的一個子集。這就是該資源的summary representation。(一些attributes是很耗費計算資源的。考慮到性能,summary representation排除了那些attributes。如果想要獲取那些attributes,請索要"detailed" representation。)
例子:當你得到一個repositories的列表時,你會得到每個repository的summary representation。
這里,我們索要octokit組織所擁有的repositories列表:
GET /orgs/octokit/repos
Detailed Representations 詳細描述
當你索要一個具體的資源時,響應通常會包含該資源的所有attributes。這就是該資源的"detailed" representation。(注意,有時候授權會影響詳細信息的總量。)
例子:當你得到一個具體的repository時,你會得到該repository的detailed representation。
這里,我們索要octokit/octokit.rb repository:
GET /repos/octokit/octokit.rb
本文檔為每個API method提供了一個示例響應。這些示例響應演示了由method返回的所有attributes。
很多API methods接受可選參數。對於GET請求,任何木有出現在path中的參數,都可以作為HTTP query string parameter傳遞:
curl -i "https://api.github.com/repos/vmg/redcarpet/issues?state=closed"
在這個例子中,vmg和redcarpet的值是提供給 :owner和 :repo parameters的,而 :state則以query string傳遞。
對於POST、PATCH、PUT、以及DELETE 請求,不包含在URL中的parameters應該被編碼成JSON,Content-Type應該是application/json。
curl -i -u username -d '{"scopes":["public_repo"]}' https://api.github.com/authorizations
你可以針對root endpoint發起一個GET請求,以獲取該endpoint的所有categories -- API支持的:
curl https://api.github.com
當API調用接收請求體時,根據請求體的不同,有三種類型的可能的客戶端錯誤。
1、發送無效JSON 會導致一個 "404 Bad Request" 響應。
HTTP/1.1 400 Bad Request Content-Length: 35 {"message":"Problems parsing JSON"}
2、發送錯誤類型的JSON值 會導致一個 "404 Bad Request" 響應。
HTTP/1.1 400 Bad Request Content-Length: 40 {"message":"Body should be a JSON object"}
3、發送無效字段會導致一個 "422 Unprocessable Entity" 響應。
HTTP/1.1 422 Unprocessable Entity Content-Length: 149 { "message": "Validation Failed", "errors": [ { "resource": "Issue", "field": "title", "code": "missing_field" } ] }
所有錯誤對象都有資源和字段properties,所以你的客戶端可以找出問題所在。
也有一個錯誤碼,可以讓你知道該字段的問題。這里是可能的校驗錯誤碼:
| Error Name | Description |
|---|---|
missing |
資源不存在 |
missing_field |
針對該資源的一個必需字段沒有設置。 |
invalid |
一個字段的格式是無效的。該資源的文檔應該會給你更多詳細信息。 |
already_exists |
另一個資源擁有相同的值。當資源必需擁有一些唯一鍵時會發生這種情況。 |
資源也可能發送自定義的校驗錯誤(code 是custom 時)。自定義錯誤通常擁有一個message 字段來描述錯誤,且多數錯誤會包含一個documentation_url 字段 -- 指向一些可能有助於解決問題的內容。
API v3 會在恰當的時候使用HTTP重定向。客戶端應該假定任意請求都可能導致重定向。接收到一個HTTP重定向不是錯誤,客戶端應該跟隨那個重定向。
重定向響應會有一個Location header字段,該字段包含了客戶端應該重新請求的URI。
| Status Code | Description |
|---|---|
301 |
永久重定向。 |
302, 307 |
臨時重定向 |
也可能使用其它重定向狀態碼,但都會遵守HTTP 1.1 spec。
只要條件允許,API v3都會爭取為每個操作使用恰當的HTTP 動詞。
| Verb | Description |
|---|---|
HEAD |
Can be issued against any resource to get just the HTTP header info. |
GET |
用於獲取資源 |
POST |
用於創建資源 |
PATCH |
Used for updating resources with partial JSON data. For instance, an Issue resource has title and body attributes. A PATCH request may accept one or more of the attributes to update the resource. PATCH is a relatively new and uncommon HTTP verb, so resource endpoints also accept POST requests. |
PUT |
Used for replacing resources or collections. For PUT requests with no body attribute, be sure to set the Content-Length header to zero.用於替換資源或集合。 |
DELETE |
用於刪除資源 |
想要通過Github API v3認證,有三種方式。 那些需要認證的請求,在一些情況下,會返回 "404 Not Found",而不是 "403 Forbidden"。這是為了防止泄露隱私。
Basic Authentication 基本認證
curl -u "username" https://api.github.com
OAuth2 Token (sent in a header)
curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com
OAuth2 Token (sent as a parameter)
curl https://api.github.com/?access_token=OAUTH-TOKEN
更多詳見 more about OAuth2。注意,OAuth2 tokens 可以通過編碼式獲取: acquired programmatically。
OAuth2 Key/Secret
curl 'https://api.github.com/users/whatever?client_id=xxxx&client_secret=yyyy'
這個應該只能用於服務器到服務器的場景。不要泄露你的OAuth 應用的客戶端secret。
Read more about unauthenticated rate limiting.
Failed login limit 登陸失敗限制
帶有無效的credentials的認證會返回 "401 Unauthorized":
curl -i https://api.github.com -u foo:bar HTTP/1.1 401 Unauthorized { "message": "Bad credentials", "documentation_url": "https://developer.github.com/v3" }
在短時間內探測到幾個帶有無效credentials的請求時,API會臨時拒絕該用戶的所有認證請求(哪怕帶有正確的credentials),返回"403 Forbidden":
curl -i https://api.github.com -u valid_username:valid_password HTTP/1.1 403 Forbidden
{ "message": "Maximum number of login attempts exceeded. Please try again later.", "documentation_url": "https://developer.github.com/v3" }
所有的資源都可能擁有一個或多個鏈接到其它資源的 *_url properties。這些是用於提供顯式的URLs,客戶端不需要自己構建它們。非常推薦客戶端使用這些。 這樣做會讓API未來的升級變得更簡單 -- 對開發者來說。所有的URLs都預期符合 RFC 6570 URI templates。
通過使用類似於 uri_template gem的東西,你可以擴展這些模板:
>> tmpl = URITemplate.new('/notifications{?since,all,participating}') >> tmpl.expand => "/notifications" >> tmpl.expand :all => 1 => "/notifications?all=1" >> tmpl.expand :all => 1, :participating => 1 => "/notifications?all=1&participating=1"
那些返回多個items的請求,會被分頁,默認每頁30個items。你可以通過 "?page" parameter來指定頁面。對於某些資源來說,你還可以通過"?per_page" parameter來設置一個自定義的頁面size,最大100。 注意,由於技術原因,不是所有的endpoints都支持"?per_page" parameter,例如,events。
curl 'https://api.github.com/user/repos?page=2&per_page=100'
注意,page的數字從1開始,如果忽略"?page" parameter,那會返回第一頁。
更多信息,見Traversing with Pagination。
Link Header 連接頭
注意:調用的時候帶有Link header 值而非自己構建,是很重要的。
Link header 包含分頁信息:
Link: <https://api.github.com/user/repos?page=3&per_page=100>; rel="next", <https://api.github.com/user/repos?page=50&per_page=100>; rel="last"
該例子包含了一個換行,僅是為了可讀
該Link 響應頭包含了一個或多個 Hypermedia link relations,其中一些可能require expansion as URI templates 。
可能的 rel 值:
| Name | Description |
|---|---|
next |
The link relation for the immediate next page of results. |
last |
The link relation for the last page of results. |
first |
The link relation for the first page of results. |
prev |
The link relation for the immediate previous page of results. |
對於那些使用Basic Authentication 或者 OAuth的請求來說,最多每小時可以請求5000次。對於那些沒有授權的請求來說,該限制是60。
未授權的請求是與你的IP關聯的,而非發起請求的user。注意: the Search API has custom rate limit rules。
你可以檢查任何API請求返回的HTTP headers,里面帶有rate limit status:
curl -i https://api.github.com/users/whatever HTTP/1.1 200 OK Date: Mon, 01 Jul 2013 17:27:06 GMT Status: 200 OK X-RateLimit-Limit: 60 X-RateLimit-Remaining: 56 X-RateLimit-Reset: 1372700873
這些headers會告訴你所有有關速率限制狀態的信息:
| Header Name | Description |
|---|---|
X-RateLimit-Limit |
The maximum number of requests that the consumer is permitted to make per hour. |
X-RateLimit-Remaining |
The number of requests remaining in the current rate limit window. |
X-RateLimit-Reset |
The time at which the current rate limit window resets in UTC epoch seconds. |
如果你需要另一種格式的時間,任何現代語言都可以做到。略。
一旦你達到了速率限制,你會收到一個錯誤響應:
HTTP/1.1 403 Forbidden Date: Tue, 20 Aug 2013 14:50:41 GMT Status: 403 Forbidden X-RateLimit-Limit: 60 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1377013266 { "message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)", "documentation_url": "https://developer.github.com/v3/#rate-limiting" }
You can also check your rate limit status without incurring an API hit.
Increasing the unauthenticated rate limit for OAuth applications 為OAuth應用提高未授權速率限制
只需要將你的app的客戶端ID和secret 作為query string傳遞過去即可:
curl -i 'https://api.github.com/users/whatever?client_id=xxxx&client_secret=yyyy' HTTP/1.1 200 OK Date: Mon, 01 Jul 2013 17:27:06 GMT Status: 200 OK X-RateLimit-Limit: 5000 X-RateLimit-Remaining: 4966 X-RateLimit-Reset: 1372700873
該方法應該僅被用於服務端到服務端的請求!
Staying within the rate limit
如果你在使用Basic Authentication或者 OAuth,當你超出了你的rate limit時,可以通過緩沖API響應、並使用 conditional requests來修復該問題。
Abuse Rate Limits 針對濫用的速率限制
為了保護GitHub的服務質量,對某些行為可能有額外的rate limit。
例如,快速地創建內容、瘋狂地輪詢而非使用webhooks、高並發地調用API、或者重復地請求耗費計算資源的數據,都會導致abuse rate limiting。
如果你的應用觸發了該速率限制,你會收到一個信息響應:
HTTP/1.1 403 Forbidden Content-Type: application/json; charset=utf-8 Connection: close { "message": "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later.", "documentation_url": "https://developer.github.com/v3#abuse-rate-limits" }
所有API請求必需包含一個有效的User-Agent header, 否則該請求會被拒絕。我們請求你使用你的GitHub用戶名、或者你應用的名字作為User-Agent header value。
一個例子:
User-Agent: Awesome-Octocat-App
如果你提供了一個無效的User-Agent header,你會收到一個 "403 Forbidden" 響應:
curl -iH 'User-Agent: ' https://api.github.com/meta HTTP/1.0 403 Forbidden Connection: close Content-Type: text/html Request forbidden by administrative rules. Please make sure your request has a User-Agent header. Check https://developer.github.com for other possible causes.
多數響應都會返回一個Etag header。很多響應也會返回一個 Last-Modified header。你可以使用這些headers的值來對同一個資源進行后續請求 -- 相應地使用"If-None-Match" 或 "If-Modified-Since" headers。如果資源沒有改變,服務器會返回 "304 Not Modified"。
注意:發起條件請求、並接收到304響應,不會計入你的rate limit, 所以我們鼓勵你使用它。
curl -i https://api.github.com/user HTTP/1.1 200 OK Cache-Control: private, max-age=60 ETag: "644b5b0155e6404a9cc4bd9d8b1ae730" Last-Modified: Thu, 05 Jul 2012 15:31:30 GMT Status: 200 OK Vary: Accept, Authorization, Cookie X-RateLimit-Limit: 5000 X-RateLimit-Remaining: 4996 X-RateLimit-Reset: 1372700873 curl -i https://api.github.com/user -H 'If-None-Match: "644b5b0155e6404a9cc4bd9d8b1ae730"' HTTP/1.1 304 Not Modified Cache-Control: private, max-age=60 ETag: "644b5b0155e6404a9cc4bd9d8b1ae730" Last-Modified: Thu, 05 Jul 2012 15:31:30 GMT Status: 304 Not Modified Vary: Accept, Authorization, Cookie X-RateLimit-Limit: 5000 X-RateLimit-Remaining: 4996 X-RateLimit-Reset: 1372700873 curl -i https://api.github.com/user -H "If-Modified-Since: Thu, 05 Jul 2012 15:31:30 GMT" HTTP/1.1 304 Not Modified Cache-Control: private, max-age=60 Last-Modified: Thu, 05 Jul 2012 15:31:30 GMT Status: 304 Not Modified Vary: Accept, Authorization, Cookie X-RateLimit-Limit: 5000 X-RateLimit-Remaining: 4996 X-RateLimit-Reset: 1372700873
--奇怪,怎么我這里只有Etag,內容為空?難道是因為沒有登陸?
Cross Origin Resource Sharing 跨域資源共享
API 支持AJAX請求從任何origin進行跨域資源共享CORS。 You can read the CORS W3C Recommendation, or this intro from the HTML 5 Security Guide.
一個示例請求,由瀏覽器發起:
curl -i https://api.github.com -H "Origin: http://example.com" HTTP/1.1 302 Found Access-Control-Allow-Origin: * Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval Access-Control-Allow-Credentials: true
這是CORS 請求:
curl -i https://api.github.com -H "Origin: http://example.com" -X OPTIONS HTTP/1.1 204 No Content Access-Control-Allow-Origin: * Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-GitHub-OTP, X-Requested-With Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval Access-Control-Max-Age: 86400 Access-Control-Allow-Credentials: true
你可以發送一個 "?callback" parameter 到任意GET call,以讓結果封裝進一個JSON function。
curl https://api.github.com?callback=foo /**/foo({ "meta": { "status": 200, "X-RateLimit-Limit": "5000", "X-RateLimit-Remaining": "4966", "X-RateLimit-Reset": "1372700873", "Link": [ // pagination headers and other links ["https://api.github.com?page=2", {"rel": "next"}] ] }, "data": { // the data } })
-- 補充:所有數據都被封裝進函數里啦。
你可以寫一個JavaScript handler來處理該回調。下面是一個最小的示例:
<html> <head> <script type="text/javascript"> function foo(response) { var meta = response.meta; var data = response.data; console.log(meta); console.log(data); } var script = document.createElement('script'); script.src = 'https://api.github.com?callback=foo'; document.getElementsByTagName('head')[0].appendChild(script); </script> </head> <body> <p>Open up your browser's console.</p> </body> </html>
所有的headers 都是與HTTP Headers相同的字符串,除了一個明顯的例外:Link。Link headers 都是預解析好的,[url, options] tuples組成的array。
一個link看起來是這樣的:
Link: <url1>; rel="next", <url2>; rel="foo"; bar="baz"
在回調輸出里是這樣的:
{ "Link": [ [ "url1", { "rel": "next" } ], [ "url2", { "rel": "foo", "bar": "baz" } ] ] }
一些請求允許指定或生成 帶有時區信息的時間戳。
我們使用下面的規則,按優先級排序,來決定API調用的時區信息。
Explicitly provide an ISO 8601 timestamp with timezone information 顯式地提供一個帶有時區信息的ISO8601時間戳
對於那些允許指定時間戳的API調用,我們會使用指定的那個時間戳。關於如何指定時間戳,不妨看一下這個例子:this example。
Using the Time-Zone header 使用Time-Zone header
根據list of names from the Olson database,使用Time-Zone header也是可以的。
curl -H "Time-Zone: Europe/Amsterdam" -X POST https://api.github.com/repos/github/linguist/contents/new_file.md
這意味着,我們會根據該header定義的timezone來生成一個時間戳。例如, Contents API 生成一個git commit時,會使用當前時間作為時間戳。該header 會決定生成時間戳的timezone。
Using the last known timezone for the user 使用用戶上一次已知的時區
如果沒有指定Time-Zone header,你可以進行一個認證過的請求,我們會使用用戶上一次已知的時區。
上一次已知的時區會隨時更新 -- 只要你瀏覽了GitHub網站。
UTC
如果上面的步驟都不起作用,我們會使用UTC作為時區來創建git commit。
