Simple and concise HTTP client library for Scala

后端 未结 11 1853
梦如初夏
梦如初夏 2020-12-12 20:26

I need a mature HTTP client library that is idiomatic to scala, concise in usage, simple semantics. I looked at the Apache HTTP and the Scala Dispatch and numerous new libra

11条回答
  •  醉话见心
    2020-12-12 20:38

    sttp is the Scala HTTP library we've all been waiting for!

    It has a fluent DSL for forming and executing requests (code samples from their README):

    val request = sttp
      .cookie("session", "*!@#!@!$")
      .body(file) // of type java.io.File
      .put(uri"http://httpbin.org/put")
      .auth.basic("me", "1234")
      .header("Custom-Header", "Custom-Value")
      .response(asByteArray)
    

    It supports synchronous, asynchronous, and streaming calls via pluggable backends, including Akka-HTTP (formerly Spray) and the venerable AsyncHttpClient (Netty):

    implicit val sttpHandler = AsyncHttpClientFutureHandler()
    val futureFirstResponse: Future[Response[String]] = request.send()
    

    It supports scala.concurrent.Future, scalaz.concurrent.Task, monix.eval.Task, and cats.effect.IO - all the major Scala IO monad libraries.

    Plus it has a few additional tricks up its sleeve:

    • It has case class representations for both requests and responses (although it doesn't go as far as having e.g. strongly typed headers): https://github.com/softwaremill/sttp/blob/master/core/src/main/scala/com/softwaremill/sttp/RequestT.scala https://github.com/softwaremill/sttp/blob/master/core/src/main/scala/com/softwaremill/sttp/Response.scala

    • It provides a URI string interpolator:

    val test = "chrabąszcz majowy" val testUri: Uri = uri"http://httpbin.org/get?bug=$test"

    • It supports encoders/decoders for request bodies/responses e.g. JSON via Circe:

    import com.softwaremill.sttp.circe._ val response: Either[io.circe.Error, Response] = sttp .post(uri"...") .body(requestPayload) .response(asJson[Response]) .send()

    Finally, it's maintained by the reliable folks at softwaremill and it's got great documentation.

提交回复
热议问题