Developus
Developus

Reputation: 1462

Scala, Hammock - retrieve http response headers and convert JSON to custom object

I have created a simple program which use Hammock(https://github.com/pepegar/hammock) and now I would like to get response from github API with reposne's headers. I created a code like this:

object GitHttpClient extends App {
  implicit val decoder = jsonOf[IO, List[GitRepository]]
  implicit val interpreter = ApacheInterpreter.instance[IO]

  val response = Hammock
    .request(Method.GET, uri"https://api.github.com/orgs/github/repos?per_page=3", Map())
    .as[List[GitRepository]]
    .exec[IO]
    .unsafeRunSync()

  println(response)
}

case class GitRepository(full_name: String, contributors_url: String)

And it works fine, I got Git data mapped to my object. But now I also want to get headers from response and I cannot do this by simple response.headers. Only when I remove .as[List[GitRepository]] line and have whole HttpResponse I could access headers. Is it possible to get headers without parsing whole HttpResponse?

Upvotes: 0

Views: 196

Answers (1)

Developus
Developus

Reputation: 1462

I solved this problem by using Decoder after received reponse:

 val response = Hammock
    .request(Method.GET, uri"https://api.github.com/orgs/github/repos?per_page=3", Map())
    .exec[IO]
    .unsafeRunSync()

    println(response.headers("Link") contains ("next"))
    println(HammockDecoder[List[GitRepository]].decode(response.entity))

Upvotes: 0

Related Questions