Created
March 6, 2014 02:44
-
-
Save brentsowers1/9381255 to your computer and use it in GitHub Desktop.
Github API example creating a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dispatch._ | |
import net.liftweb.json._ | |
// Nothing to this class | |
class GithubClass | |
/** | |
* A github user | |
*/ | |
case class User(login: String, // login name of hte user | |
id: Int, // numeric github ID | |
avatar_url: String, // URL to their avatar pic | |
url: String) // API url to retrieve JSON of the user | |
extends GithubClass | |
/** | |
* A single code repo. | |
*/ | |
case class Repo(name: String, | |
clone_url: String) | |
extends GithubClass | |
class GithubApi { | |
// Needed for Lift JSON, don't remove/modify | |
implicit val formats = net.liftweb.json.DefaultFormats | |
/** | |
* Makes an HTTP request to Github, and returns the response as a list | |
* of the class that you specify in [] when calling this | |
*/ | |
def getData[T <: GithubClass : Manifest](path: String) : List[T] = { | |
val h = new Http | |
val req = url("https://api.github.com/" + path) | |
// Gets both the headers and response body | |
val rspStr = h(req as_str) | |
val rspJVal = parse(rspStr) | |
val rspList = rspJVal.children | |
for (jObj <- rspList) yield jObj.extract[T] | |
} | |
} | |
val gh = new GithubApi | |
val repos = gh.getData[Repo]("users/brentsowers1/repos") | |
for (repo <- repos) { | |
println("Repo name: " + repo.name) | |
println("Clone url: " + repo.clone_url) | |
} | |
val users = gh.getData[User]("repos/brentsowers1/googlestaticmap/watchers") | |
for (user <- users) { | |
println("Watcher login: " + user.login) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment