Github APIを使うためのaccess tokenを取得する
本来であればOAuth認証でaccess tokenを取得するべきなのだろうけれども、HTTPSのBasic認証でも取得できるらしいのでやってみた。
access tokenを取得する
https://help.github.com/articles/creating-an-oauth-token-for-command-line-use
上記URLの通りに叩くだけ
$ curl -u 'username' -d '{"scopes":["repo"],"note":"Help example"}' https://api.github.com/authorizations
scopesのところは http://developer.github.com/v3/oauth/#scopes を見つつ、やりたいことに応じて指定する。
取得してみた
% curl -u 'username' -d '{"scopes":["repo"],"note":"Help example"}' https://api.github.com/authorizations Enter host password for user 'username': # usernameに対するパスワードを入力 { "app": { "name": "Help example (API)", "url": "http://developer.github.com/v3/oauth/#oauth-authorizations-api" }, "scopes": [ "repo" ], "created_at": "2012-09-30T14:02:09Z", "note_url": null, "note": "Help example", "token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "updated_at": "2012-09-30T14:02:09Z", "id": 000000, "url": "https://api.github.com/authorizations/000000" }
※ username、token、id、urlはブログ掲載にあたり書き換えている。
あと、https://github.com/settings/applications にアクセスすると、Authorized applicationsに"Help example (API) access private repos"が追加されている。
access tokenを使ってのAPIを叩いてみる
リクエスト時のheaderのAuthorizationで指定してあげればいいらしい。
% curl -H "Authorization: token xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" https://api.github.com/user # 結果は省略
リクエストパラメータで渡すこともできるらしい。
% curl "https://api.github.com/user?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 結果は省略
はまったこと
% curl -H "Authorization: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" https://api.github.com/user { "message": "Bad credentials" }
"Bad credentials"と言われて、??となったのだけれども、Authorization:のあとに"token"が抜けていた。