miércoles, 8 de junio de 2022

sttp: ¡el cliente Scala HTTP que siempre quisiste!


sttp es un cliente http, simple que permite manejar las respuestas. sttp proporciona interfaces tanto síncronas como asíncronas, procedimentales y funcionales.

Las implementaciones incluyen aquellas basadas en clientes akka-http, async-http-client, http4s, OkHttp y HTTP que se envían con Java. Se integran con Akka, Monix, fs2, cats-effect, scalaz y ZIO. Las versiones de Scala admitidas incluyen 2.11, 2.12, 2.13 y 3, Scala.JS y Scala Native.

Veamos un pequeño ejemplo: 

// In addition to the usual values brought into scope by `sttp.client3._`,

// the `quick` version also defines a default synchronous `backend`.

import sttp.client3.quick._

// Circe integration: `asJson` response description.

import sttp.client3.circe._


import io.circe.generic.auto._


// Case classes corresponding to the json returned by GitHub (just the 

// fields that interest us).

case class GitHubResponse(total_count: Int, items: List[GitHubItem])

case class GitHubItem(name: String, stargazers_count: Int)


val query = "language:scala"

val sort: Option[String] = Some("stars")


// Describing the request: specifying the method, uri and how to handle

// the response. The `query` parameter is automatically url-encoded

// `sort` will be unwrapped if `Some(_)`, and removed if `None`.

val request = basicRequest

  .get(uri"https://api.github.com/search/repositories?q=$query&sort=$sort")

  .response(asJson[GitHubResponse])

  

// As we are using the synchronous `HttpURLConnectionBackend`, `send()` will 

// return `Response[_]`. Async backends return e.g. `Future[Response[_]]`.

val response = request.send(backend)

// The body will be a `Left(_)` in case of a non-2xx response, or a json

// deserialization error. It will be `Right(_)` otherwise.

response.body match {

  case Left(error) => println(s"Error when executing request: $error")

  case Right(data) =>

    println(s"Found ${data.total_count} Scala projects.")

    println(s"Showing ${data.items.size} with most stars:")

    data.items.foreach { item =>

      println(s"  ${item.name} (${item.stargazers_count})")

    }

}

Dejo link : https://sttp.softwaremill.com/en/latest/


No hay comentarios.:

Publicar un comentario