Skip to content

Instantly share code, notes, and snippets.

@azugxi7374
Last active August 29, 2015 13:56
Show Gist options
  • Save azugxi7374/9212537 to your computer and use it in GitHub Desktop.
Save azugxi7374/9212537 to your computer and use it in GitHub Desktop.
GitHub APIのメモ

dispatch+json4sの使い方

dispatchでHTTP通信。as.json4s.Jsonするとjson4sになる

val dispatchVersion = "0.11.0"
libraryDependencies ++= Seq(
  "net.databinder.dispatch" %% "dispatch-core" % dispatchVersion,
  "net.databinder.dispatch" %% "dispatch-jsoup" % dispatchVersion,
  "net.databinder.dispatch" %% "dispatch-json4s-native" % dispatchVersion,
  "org.slf4j" % "slf4j-log4j12" % "1.7.6"
)
import dispatch._, Defaults._
import org.json4s._, native.JsonMethods._, JsonDSL._

// json取得
val urlstr = "https://api.github.com/repos/ixxa/procon-lib"
val json = Http(url(urlstr) OK as.json4s.Json).apply
/*
↑json
{
  "id": 17081970,
  "name": "procon-lib",
  "full_name": "ixxa/procon-lib",
  "owner": {
    "login": "ixxa",
    "id": 3647920,
		...
*/

// XPath方式が楽
val name = compact(render(json \\ "name")) // => "procon-lib"
val ownerID = compact(render(json \ "owner" \ "id")) // => 3647920
  • dispatchはrebootとclassicがある。rebootが新しいが資料が少なくてつらい
  • dispatchでHttp()呼ぶときなんか警告が出る。けど動いてるからとりあえず放置
  • json4sはnativeとjacksonがある。違いがよくわからない
  • json4sを依存関係に入れてないけどdispatch-json4s-nativeが勝手に持ってきてくれてる?

リポジトリ情報を取得するAPIのメモ

Get Contensのところに書いてあるまま GET /repos/:owner/:repo/contents/:path

フォルダの場合

jsonにする

val req = url("https://api.github.com/repos/ixxa/procon-lib/contents/lib")
val json = Http(req OK as.json4s.Json).apply

ファイルの場合

contentがencodeされているのでrawファイルが欲しければAcceptにMediaTypeを追加。dispatchでは<:<を使う

val req = url("https://api.github.com/repos/ixxa/procon-lib/contents/lib/gcd.java") <:< 
  Map("Accept" -> "application/vnd.github.v3.raw")
val raw = Http(res30 OK as.String).apply

API制限について

同IPから1時間に60回。response headerのX-RateLimit-Remainingが残り回数。 認証すると5000回になる。

認証方法

  1. username, passwordを使う方法 request headerに加える。url("url").as_!("username", "password")

  2. access token account settings -> applications -> generate new token で発行し、headerまたはURL引数へ。
    https://help.github.com/articles/creating-an-access-token-for-command-line-use

  3. OAuth https://developer.github.com/v3/oauth/#non-web-application-flow
    あとで読む

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment