Last active
February 3, 2026 20:19
-
-
Save dacr/7906717f02d138756353c1758098bd0f to your computer and use it in GitHub Desktop.
Simplest sttp http client library json example using akkahttp backend. / published by https://github.com/dacr/code-examples-manager #2b623f40-e7df-4fb8-8b29-05d7907d63a0/88f28e35af7df769d16793112370cc26dbac6e91
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
| // summary : Simplest sttp http client library json example using akkahttp backend. | |
| // keywords : scala, sttp, http-client, json4s, json, akkahttp | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 2b623f40-e7df-4fb8-8b29-05d7907d63a0 | |
| // created-on : 2020-07-02T10:02:26Z | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // execution : scala ammonite script (http://ammonite.io/) - run as follow 'amm scriptname.sc' | |
| import $ivy.`com.softwaremill.sttp.client3::core:3.3.5` | |
| import $ivy.`com.softwaremill.sttp.client3::akka-http-backend:3.3.5` | |
| import $ivy.`com.softwaremill.sttp.client3::json4s:3.3.5` | |
| import $ivy.`com.typesafe.akka::akka-stream:2.6.14` | |
| import $ivy.`org.json4s::json4s-jackson:3.6.11` | |
| import sttp.client3._ | |
| import sttp.client3.json4s._ | |
| import org.json4s._ | |
| import sttp.client3.akkahttp._ | |
| import scala.util.{Success, Failure, Try, Left, Right, Either} | |
| import scala.concurrent.{Future, Await} | |
| import scala.concurrent.duration._ | |
| object Status { // Embedded within an object to avoid issues between future and ammonite | |
| import scala.concurrent.ExecutionContext.Implicits.global | |
| val backend = AkkaHttpBackend() | |
| implicit val serialization = org.json4s.jackson.Serialization | |
| implicit val formats = org.json4s.DefaultFormats | |
| def check():Unit = { | |
| val jsonFuture = { | |
| basicRequest | |
| .get(uri"http://httpbin.org/ip") | |
| .response(asJson[JValue]) | |
| .send(backend) | |
| } | |
| val resultFuture = { | |
| jsonFuture | |
| .map(_.body) | |
| .collect { case Right(json) => json } | |
| .map(json => (json \ "origin").extract[String]) | |
| } | |
| Await.result(resultFuture.map(println), 2.seconds) // To avoid exiting before the result is ready to be printed | |
| } | |
| } | |
| Status.check() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment