Last active
May 25, 2024 10:19
-
-
Save dacr/7a4dc5c4eafce54264e4f578df4334bb to your computer and use it in GitHub Desktop.
Simplest sttp http client library json example. / published by https://github.com/dacr/code-examples-manager #24dc9898-25f9-42af-b4e0-8e8b2cfe18dc/180f079b62e96425a485048df63d9f5d813d51b
This file contains 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
// summary : Simplest sttp http client library json example. | |
// keywords : scala, sttp, http-client, json4s, json | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 24dc9898-25f9-42af-b4e0-8e8b2cfe18dc | |
// created-on : 2019-05-19T16:59:54Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "com.softwaremill.sttp.client3::core:3.7.0" | |
//> using dep "com.softwaremill.sttp.client3::json4s:3.7.0" | |
// --------------------- | |
import sttp.client3.* | |
import sttp.client3.json4s.* | |
import org.json4s.JValue | |
import org.json4s.jackson.Serialization | |
import org.json4s.* | |
implicit val serialization:Serialization.type = org.json4s.jackson.Serialization | |
implicit val formats:Formats = org.json4s.DefaultFormats | |
val result = | |
quickRequest | |
.get(uri"http://httpbin.org/ip") | |
.response(asJson[JValue]) | |
.send(quick.backend) | |
// Various way to deal with the result | |
result.body.toSeq.flatMap{ case json => (json \ "origin").extractOpt[String] }.foreach(println) | |
result.body.map(json => (json \ "origin").extract[String] ).foreach(println) | |
result.body.toOption.map(_ \ "origin").flatMap(_.extractOpt[String]).foreach(println) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment