### Send a GET Request with Quickstart Source: https://sttp.softwaremill.com/en/stable/quickstart.html Use `import sttp.client4.quick.*` to access a pre-configured synchronous backend and `quickRequest` for sending requests. The `quickRequest` automatically reads responses as Strings. ```scala import sttp.client4.quick.* quickRequest.get(uri"http://httpbin.org/ip").send() ``` -------------------------------- ### Scala CLI Example Source: https://sttp.softwaremill.com/en/stable/backends/native/curl.html A basic Scala CLI example demonstrating the use of CurlBackend for a GET request. ```scala // hello.scala //> using platform native //> using dep com.softwaremill.sttp.client4::core_native0.5:4.0.25 import sttp.client4.* import sttp.client4.curl.CurlBackend @main def run(): Unit = val backend = CurlBackend() println(basicRequest.get(uri"http://httpbin.org/ip").send(backend)) ``` -------------------------------- ### Comprehensive URI Construction Example Source: https://sttp.softwaremill.com/en/stable/model/uri.html A detailed example combining scheme, subdomains, optional query parameters, query maps, and fragments using the 'uri' interpolator. ```Scala import sttp.client4.* val secure = true val scheme = if (secure) "https" else "http" val subdomains = List("sub1", "sub2") val vx = Some("y z") val paramMap = Map("a" -> 1, "b" -> 2) val jumpTo = Some("section2") println(uri"$scheme://$subdomains.example.com?x=$vx&$paramMap#$jumpTo") // https://sub1.sub2.example.com?x=y+z&a=1&b=2#section2 ``` -------------------------------- ### Install Node.js Fetch and WebSocket Modules (ESModule) Source: https://sttp.softwaremill.com/en/stable/backends/javascript/fetch.html Install `node-fetch` and `isomorphic-ws` for use in an ESModule bundled Scala.js application running in Node.js. ```bash npm install --save node-fetch isomorphic-ws ws ``` -------------------------------- ### Install Node.js Fetch and WebSocket Modules (CommonJS) Source: https://sttp.softwaremill.com/en/stable/backends/javascript/fetch.html Install `node-fetch` (version 2 for CommonJS compatibility) and `isomorphic-ws` for WebSocket support in Node.js environments using CommonJS modules. ```bash npm install --save node-fetch@2 isomorphic-ws ws ``` -------------------------------- ### Pekko Backend Streaming Example Source: https://sttp.softwaremill.com/en/stable/responses/body.html Example demonstrating how to use `asStreamUnsafe` with the Pekko backend to receive a response as a Pekko `Source`. ```APIDOC ## Pekko Backend Streaming Example ### Description This example demonstrates how to use `asStreamUnsafe` with the Pekko backend to receive a response as a Pekko `Source`. ### Method `basicRequest.post(uri"...").response(asStreamUnsafe(PekkoStreams)).send(backend)` ### Endpoint `POST ...` (The specific URI is determined by the `uri"..."` literal) ### Parameters - `backend`: An instance of `StreamBackend[Future, PekkoStreams]` (e.g., `PekkoHttpBackend()`) ### Request Body Not specified in the example, but implied by the `POST` method. ### Response - **Success Response**: `Future[Response[Either[String, Source[ByteString, Any]]]]` - The response body is a `Source` of `ByteString` chunks. ### Request Example ```scala import org.apache.pekko.stream.scaladsl.Source import org.apache.pekko.util.ByteString import scala.concurrent.Future import sttp.capabilities.pekko.PekkoStreams import sttp.client4._ import sttp.client4.pekkohttp.PekkoHttpBackend val backend: StreamBackend[Future, PekkoStreams] = PekkoHttpBackend() val response: Future[Response[Either[String, Source[ByteString, Any]]]] = basicRequest .post(uri"...") .response(asStreamUnsafe(PekkoStreams)) .send(backend) ``` ``` -------------------------------- ### ZIO-based Curl Backend Initialization Source: https://sttp.softwaremill.com/en/stable/backends/native/curl.html Example of initializing and using CurlZioBackend within a ZIO application, ensuring resource cleanup. ```scala //> using platform native //> using nativeVersion 0.5.10 //> using scala 3 //> using dep com.softwaremill.sttp.client4::zio::4.0.25 import sttp.client4.* import sttp.client4.curl.zio.CurlZioBackend import zio.* object Main extends ZIOAppDefault: def run = for backend <- CurlZioBackend.scoped() res <- basicRequest.get(uri"http://httpbin.org/ip").send(backend) _ <- Console.printLine(res) yield () ``` -------------------------------- ### Quick HTTP GET Request Source: https://sttp.softwaremill.com/en/stable/index.html A simple example demonstrating a GET request to retrieve IP information using scala-cli. Ensure the sttp client core dependency is added. ```scala //> using dep com.softwaremill.sttp.client4::core::4.0.25 import sttp.client4.quick.* @main def run(): Unit = println(quickRequest.get(uri"http://httpbin.org/ip").send()) ``` -------------------------------- ### Create Armeria Monix Backend Source: https://sttp.softwaremill.com/en/stable/backends/monix.html Create an asynchronous Monix-based backend using Armeria. This example shows creating a backend with the default client and using a custom-built Armeria WebClient. ```scala import sttp.client4.armeria.monix.ArmeriaMonixBackend import monix.execution.Scheduler.Implicits.global val backend = ArmeriaMonixBackend() // You can use the default client which reuses the connection pool of ClientFactory.ofDefault() ArmeriaMonixBackend.usingDefaultClient() ``` ```scala import com.linecorp.armeria.client.circuitbreaker.* import com.linecorp.armeria.client.WebClient // Fluently build Armeria WebClient with built-in decorators val client = WebClient.builder("https://my-service.com") // Open circuit on 5xx server error status .decorator(CircuitBreakerClient.newDecorator(CircuitBreaker.ofDefaultName(), CircuitBreakerRule.onServerErrorStatus())) .build() val backend = ArmeriaMonixBackend.usingClient(client) ``` -------------------------------- ### Example Multipart Request with Text, File, and Form Data Source: https://sttp.softwaremill.com/en/stable/requests/multipart.html Demonstrates creating a multipart request with a text part, a file part, and a form data part. ```scala import sttp.client4.* import java.io.* val someFile = new File("/sample/path") basicRequest.multipartBody( multipart("text_part", "data1"), multipartFile("file_part", someFile), // someFile: File multipart("form_part", Map("x" -> "10", "y" -> "yes")) ) ``` -------------------------------- ### Sending a Request using ZIO Environment Source: https://sttp.softwaremill.com/en/stable/backends/zio.html Demonstrates sending a basic GET request using the SttpClient available in the ZIO environment. This approach aligns with ZIO's style of effectful programming. ```scala import sttp.client4.* import sttp.client4.httpclient.zio.* import zio.* val request = basicRequest.get(uri"https://httpbin.org/get") val sent: ZIO[SttpClient, Throwable, Response[Either[String, String]]] = send(request) ``` -------------------------------- ### Basic Usage of Slf4jLoggingBackend Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/logging.html Example of creating and using the Slf4jLoggingBackend with a default synchronous backend. This will log request and response information using slf4j. ```scala import sttp.client4.* import sttp.client4.logging.slf4j.Slf4jLoggingBackend val backend = Slf4jLoggingBackend(DefaultSyncBackend()) basicRequest.get(uri"https://httpbin.org/get").send(backend) // Logs: // 21:14:23.735 [main] INFO sttp.client4.logging.slf4j.Slf4jTimingBackend - Request: GET https://httpbin.org/get, took: 0.795s, response: 200 ``` -------------------------------- ### Jsoniter-scala Usage Example Source: https://sttp.softwaremill.com/en/stable/other/json.html Example demonstrating JSON encoding and decoding with jsoniter-scala, including codec definitions and request/response handling. ```scala import sttp.client4.* import sttp.client4.jsoniter._ import com.github.plokhotnyuk.jsoniter_scala.core.* import com.github.plokhotnyuk.jsoniter_scala.macros.* val backend: SyncBackend = DefaultSyncBackend() implicit val payloadJsonCodec: JsonValueCodec[RequestPayload] = JsonCodecMaker.make //note that the jsoniter doesn't support 'implicit defs' and so either has to be generated seperatly implicit val jsonEitherDecoder: JsonValueCodec[ResponsePayload] = JsonCodecMaker.make val requestPayload = RequestPayload("some data") val response: Response[Either[ResponseException[String], ResponsePayload]] = basicRequest .post(uri"...") .body(asJson(requestPayload)) .response(asJson[ResponsePayload]) .send(backend) ``` -------------------------------- ### Usage Example for XML Serialization/Deserialization Source: https://sttp.softwaremill.com/en/stable/other/xml.html Demonstrates how to use the asXml methods for sending and receiving XML data with sttp. This example assumes `Outer` and `Inner` classes are generated by scalaxb and the necessary `XMLFormat` and `XmlElementLabel` are in scope. ```scala val backend: SyncBackend = DefaultSyncBackend() // `Outer` and `Inner` classes are generated by scalaxb from xsd file val requestPayload = Outer(Inner(42, b = true, "horses"), "cats") // imports sttp related serialization / deserialization logic import sttpScalaxb.* // gives needed XmlElementLabel for the top XML node given XmlElementLabel = XmlElementLabel("outer") // imports member of code generated by scalaxb, that provides `XMLFormat` for `Outer` type; // this import may differ depending on location of generated code import generated.Generated_OuterFormat val response: Response[Either[ResponseException[String], Outer]] = basicRequest .post(uri"...") .body(asXml(requestPayload)) .response(asXml[Outer]) .send(backend) ``` -------------------------------- ### uPickle Usage Example Source: https://sttp.softwaremill.com/en/stable/other/json.html Example demonstrating JSON encoding and decoding with uPickle, including ReadWriter definitions and request/response handling. ```scala import sttp.client4.* import sttp.client4.upicklejson.default._ import upickle.default.* val backend: SyncBackend = DefaultSyncBackend() implicit val requestPayloadRW: ReadWriter[RequestPayload] = macroRW[RequestPayload] implicit val responsePayloadRW: ReadWriter[ResponsePayload] = macroRW[ResponsePayload] val requestPayload = RequestPayload("some data") val response: Response[Either[ResponseException[String], ResponsePayload]] = basicRequest .post(uri"...") .body(asJson(requestPayload)) .response(asJson[ResponsePayload]) .send(backend) ``` -------------------------------- ### Spray-json Usage Example Source: https://sttp.softwaremill.com/en/stable/other/json.html Example of sending and receiving JSON using the spray-json backend. Requires implicit JsonWriter/JsonReader or JsonFormat instances. ```scala import sttp.client4.* import sttp.client4.sprayJson.* import spray.json.* val backend: SyncBackend = DefaultSyncBackend() implicit val payloadJsonFormat: RootJsonFormat[RequestPayload] = ??? implicit val myResponseJsonFormat: RootJsonFormat[ResponsePayload] = ??? val requestPayload = RequestPayload("some data") val response: Response[Either[ResponseException[String], ResponsePayload]] = basicRequest .post(uri"...") .body(asJson(requestPayload)) .response(asJson[ResponsePayload]) .send(backend) ``` -------------------------------- ### Zio-json Usage Example Source: https://sttp.softwaremill.com/en/stable/other/json.html Example of sending and receiving JSON using the zio-json backend. Requires implicit JsonEncoder/JsonDecoder or JsonCodec. ```scala import sttp.client4.* import sttp.client4.ziojson.* import zio.json.* val backend: SyncBackend = DefaultSyncBackend() implicit val payloadJsonEncoder: JsonEncoder[RequestPayload] = DeriveJsonEncoder.gen[RequestPayload] implicit val myResponseJsonDecoder: JsonDecoder[ResponsePayload] = DeriveJsonDecoder.gen[ResponsePayload] val requestPayload = RequestPayload("some data") val response: Response[Either[ResponseException[String], ResponsePayload]] = basicRequest .post(uri"...") .body(asJson(requestPayload)) .response(asJson[ResponsePayload]) .send(backend) ``` -------------------------------- ### Basic Request with Header and URI Source: https://sttp.softwaremill.com/en/stable/model/model.html Demonstrates creating a basic GET request with a Content-Type header and a URI using sttp model classes. ```scala import sttp.client4.* import sttp.model.* object Example: val request = basicRequest.header(Header.contentType(MediaType.ApplicationJson)) .get(uri"https://httpbin.org") val backend = DefaultSyncBackend() val response = request.send(backend) if response.code == StatusCode.Ok then println("Ok!") ``` -------------------------------- ### Json4s Usage Example Source: https://sttp.softwaremill.com/en/stable/other/json.html Example of sending and receiving JSON using the json4s backend. Requires implicit Serialization and Formats. ```scala import org.json4s.Formats import org.json4s.Serialization import sttp.client4.* import sttp.client4.json4s.* val backend: SyncBackend = DefaultSyncBackend() val requestPayload = RequestPayload("some data") given Serialization = org.json4s.native.Serialization given Formats = org.json4s.DefaultFormats val response: Response[Either[ResponseException[String], ResponsePayload]] = basicRequest .post(uri"...") .body(asJson(requestPayload)) .response(asJson[ResponsePayload]) .send(backend) ``` -------------------------------- ### Sending a Request and Accessing Response Source: https://sttp.softwaremill.com/en/stable/responses/basics.html Demonstrates sending a basic GET request and accessing the response using DefaultSyncBackend. Shows how to retrieve single and multiple headers, and common header values like content type and length. ```Scala import sttp.model.* import sttp.client4.* val backend = DefaultSyncBackend() val request = basicRequest.get(uri"https://httpbin.org/get") val response = request.send(backend) val singleHeader: Option[String] = response.header(HeaderNames.Server) val multipleHeaders: Seq[String] = response.headers(HeaderNames.Allow) ``` -------------------------------- ### Digest Authentication Backend Setup Source: https://sttp.softwaremill.com/en/stable/requests/authentication.html Wrap an existing backend with `DigestAuthenticationBackend` to enable digest authentication. This is necessary because digest authentication involves an additional message exchange. ```scala import sttp.client4.wrappers.DigestAuthenticationBackend val myBackend: SyncBackend = DefaultSyncBackend() DigestAuthenticationBackend(myBackend) ``` -------------------------------- ### Streaming a Response with FetchMonixBackend Source: https://sttp.softwaremill.com/en/stable/backends/javascript/fetch.html Example of how to send a POST request and receive a streaming response using FetchMonixBackend and Monix. ```scala import sttp.client4.* import sttp.client4.impl.monix.* import java.nio.ByteBuffer import monix.eval.Task import monix.reactive.Observable val backend = FetchMonixBackend() val response: Task[Response[Observable[ByteBuffer]]] = sttp .post(uri"...") .response(asStreamUnsafe(MonixStreams)) .send(backend) ``` -------------------------------- ### Using Pekko Backend for Streaming Source: https://sttp.softwaremill.com/en/stable/responses/body.html Example demonstrating how to use the Pekko backend with sttp to receive a response as an unsafe stream. This requires the PekkoStreams capability. ```scala import org.apache.pekko.stream.scaladsl.Source import org.apache.pekko.util.ByteString import scala.concurrent.Future import sttp.capabilities.pekko.PekkoStreams import sttp.client4.* import sttp.client4.pekkohttp.PekkoHttpBackend val backend: StreamBackend[Future, PekkoStreams] = PekkoHttpBackend() val response: Future[Response[Either[String, Source[ByteString, Any]]]] = basicRequest .post(uri"...") .response(asStreamUnsafe(PekkoStreams)) .send(backend) ``` -------------------------------- ### Import statements for stub backend examples Source: https://sttp.softwaremill.com/en/stable/testing/stub.html These import statements are commonly used across various examples for the stub backend. They include necessary classes from sttp.client4, sttp.model, and sttp.client4.testing, along with Scala concurrency utilities. ```Scala import sttp.client4.* import sttp.model.* import sttp.client4.testing.* import java.io.File import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global case class User(id: String) ``` -------------------------------- ### Import sttp.client4 Source: https://sttp.softwaremill.com/en/stable/requests/basics.html This import brings the necessary components into scope to start defining requests. ```scala import sttp.client4.* ``` -------------------------------- ### Custom Upickle Integration Source: https://sttp.softwaremill.com/en/stable/other/json.html Example of creating a custom integration for a customized uPickle configuration, ensuring the correct upickle API is used. ```scala import upickle.legacy.* object legacyUpickle extends sttp.client4.upicklejson.SttpUpickleApi { override val upickleApi: upickle.legacy.type = upickle.legacy } import legacyUpickle.* // use upickle as in the above examples ``` -------------------------------- ### GitHub API Search with Query Parameters Source: https://sttp.softwaremill.com/en/stable/index.html Demonstrates making a GET request to the GitHub API to search for repositories, showcasing URL encoding of query parameters and handling of optional parameters. A synchronous backend is used. ```scala //> using dep com.softwaremill.sttp.client4::core::4.0.25 import sttp.client4.* @main def sttpDemo(): Unit = val sort: Option[String] = None val query = "http language:scala" // the `query` parameter is automatically url-encoded // `sort` is removed, as the value is not defined val request = basicRequest.get( uri"https://api.github.com/search/repositories?q=$query&sort=$sort") val backend = DefaultSyncBackend() val response = request.send(backend) // response.header(...): Option[String] println(response.header("Content-Length")) // since we're using basicRequest, the response.body is read into an // Either[String, String] to indicate failure or success println(response.body) ``` -------------------------------- ### Create a default OkHttpFutureBackend Source: https://sttp.softwaremill.com/en/stable/backends/future.html Instantiate the OkHttpFutureBackend with default settings. ```scala val backend = OkHttpFutureBackend() ``` -------------------------------- ### Create OkHttpSyncBackend with Custom Client Source: https://sttp.softwaremill.com/en/stable/backends/synchronous.html Create a synchronous backend using a pre-instantiated OkHttpClient. ```scala import sttp.client4.okhttp.OkHttpSyncBackend import okhttp3.* val okHttpClient: OkHttpClient = ??? val backend = OkHttpSyncBackend.usingClient(okHttpClient) ``` -------------------------------- ### Create PekkoHttpBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/pekko.html Instantiate the PekkoHttpBackend for use in your application. This is the default way to create the backend. ```scala import sttp.client4.pekkohttp.* val backend = PekkoHttpBackend() ``` -------------------------------- ### OkHttpFutureBackend with Custom OkHttpClient Source: https://sttp.softwaremill.com/en/stable/conf/ssl.html Sets up an OkHttpFutureBackend using a custom OkHttpClient that is configured with a specific SSLContext and X509TrustManager. Required when OkHttp needs explicit trust management. ```scala import okhttp3.OkHttpClient import sttp.client4.okhttp.OkHttpFutureBackend import javax.net.ssl.X509TrustManager val yourTrustManager: X509TrustManager = ??? val client: OkHttpClient = new OkHttpClient.Builder() .sslSocketFactory(ssl.getSocketFactory, yourTrustManager) .build() val backend = OkHttpFutureBackend.usingClient(client) ``` -------------------------------- ### Create OkHttpSyncBackend Source: https://sttp.softwaremill.com/en/stable/backends/synchronous.html Instantiate the synchronous backend using OkHttp. ```scala import sttp.client4.okhttp.OkHttpSyncBackend val backend = OkHttpSyncBackend() ``` -------------------------------- ### Instantiate OpenTelemetryTracingZioBackend Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/opentelemetry.html Construct OpenTelemetryTracingZioBackend by wrapping a ZIO backend with a Tracing instance from zio-telemetry. ```scala import sttp.client4.* import zio.* import zio.telemetry.opentelemetry.tracing.* import sttp.client4.opentelemetry.zio.* val zioBackend: Backend[Task] = ??? val tracing: Tracing = ??? OpenTelemetryTracingZioBackend(zioBackend, tracing) ``` -------------------------------- ### Convert Basic GET Request to CURL Source: https://sttp.softwaremill.com/en/stable/testing/curl.html Use the `.toCurl` method on a basic GET request to generate its CURL command representation. This is useful for debugging and understanding request details. ```scala import sttp.client4.* basicRequest.get(uri"http://httpbin.org/ip").toCurl // res0: String = """curl \ // --request GET \ // --url 'http://httpbin.org/ip' \ // --header 'Accept-Encoding: gzip, deflate' \ // --location \ // --max-redirs 32""" ``` -------------------------------- ### Redirecting POST Requests to GET Source: https://sttp.softwaremill.com/en/stable/conf/redirects.html Configure requests to change the method to GET when a redirect occurs for POST or PUT requests, mimicking browser behavior. This applies to 301 and 302 redirects. ```scala import sttp.client4.* basicRequest.redirectToGet(true) ``` -------------------------------- ### Create a default ArmeriaFutureBackend Source: https://sttp.softwaremill.com/en/stable/backends/future.html Instantiate the ArmeriaFutureBackend using the default client factory. ```scala val backend = ArmeriaFutureBackend() // You can use the default client which reuses the connection pool of ClientFactory.ofDefault() ArmeriaFutureBackend.usingDefaultClient() ``` -------------------------------- ### Create ArmeriaZioBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/zio.html Instantiate the ArmeriaZioBackend using various methods, including flatMap, scoped, or by using the default client. ```scala import sttp.client4.armeria.zio.ArmeriaZioBackend ArmeriaZioBackend().flatMap { backend => ??? ``` ```scala // or, if you'd like the backend to be wrapped in a Scope: ArmeriaZioBackend.scoped().flatMap { backend => ??? ``` ```scala // You can use the default client which reuses the connection pool of ClientFactory.ofDefault() ArmeriaZioBackend.usingDefaultClient().flatMap { backend => ??? ``` -------------------------------- ### Handle Server-Sent Events with Ox Source: https://sttp.softwaremill.com/en/stable/backends/synchronous.html Example of handling Server-Sent Events as a Flow using Ox and sttp. ```scala import sttp.client4.* import sttp.client4.impl.ox.sse.OxServerSentEvents import java.io.InputStream def handleSse(is: InputStream): Unit = OxServerSentEvents.parse(is).runForeach(event => println(s"Received event: $event")) val backend = DefaultSyncBackend() basicRequest .get(uri"https://postman-echo.com/server-events/3") .response(asInputStreamAlways(handleSse)) .send(backend) ``` -------------------------------- ### Instantiate OpenTelemetryMetricsBackend Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/opentelemetry.html Obtain an instance of OpenTelemetryMetricsBackend by wrapping an existing backend and providing an OpenTelemetry instance. ```scala import scala.concurrent.Future import sttp.client4.* import sttp.client4.opentelemetry.* import io.opentelemetry.api.OpenTelemetry // any effect and capabilities are supported val sttpBackend: Backend[Future] = ??? val openTelemetry: OpenTelemetry = ??? OpenTelemetryMetricsBackend(sttpBackend, openTelemetry) ``` -------------------------------- ### Example openapi-ignore-file content Source: https://sttp.softwaremill.com/en/stable/other/openapi.html Content for the openapi-ignore-file to specify which files should be generated by openapi-generator, focusing on Scala source files. ```text * **/* !**/src/main/scala/**/* ``` -------------------------------- ### Create OkHttpFutureBackend with a custom OkHttpClient Source: https://sttp.softwaremill.com/en/stable/backends/future.html Create an OkHttpFutureBackend by providing your own instance of okhttp3.OkHttpClient. ```scala import okhttp3.OkHttpClient val okHttpClient: OkHttpClient = ??? val backend = OkHttpFutureBackend.usingClient(okHttpClient) ``` -------------------------------- ### Create FetchZioBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/javascript/fetch.html Instantiate the `FetchZioBackend` for Scala.js. This backend is suitable for ZIO-based applications. ```scala val backend = FetchZioBackend() ``` -------------------------------- ### Create HttpClientZioBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/zio.html Instantiate the HttpClientZioBackend using various methods, including flatMap, scoped, or by providing a custom HttpClient instance. ```scala import sttp.client4.httpclient.zio.HttpClientZioBackend HttpClientZioBackend().flatMap { backend => ??? } ``` ```scala // or, if you'd like the backend to be created in a Scope: HttpClientZioBackend.scoped().flatMap { backend => ??? ``` ```scala // or, if you'd like to instantiate the HttpClient yourself: import java.net.http.HttpClient val httpClient: HttpClient = ??? val backend = HttpClientZioBackend.usingClient(httpClient) ``` ```scala // or, obtain a Scope with a custom instance of the HttpClient: HttpClientZioBackend.scopedUsingClient(httpClient).flatMap { backend => ??? ``` -------------------------------- ### Map Response Body to Int Source: https://sttp.softwaremill.com/en/stable/responses/body.html Transforms a string response body into an Int. This example ignores potential exceptions during conversion. ```scala import sttp.client4.* val asInt: ResponseAs[Either[String, Int]] = asString.mapRight((_: String).toInt) basicRequest .get(uri"http://example.com") .response(asInt) ``` -------------------------------- ### Accessing Common Response Headers Source: https://sttp.softwaremill.com/en/stable/responses/basics.html Provides examples for easily accessing commonly used response headers such as Content-Type and Content-Length. ```Scala val contentType: Option[String] = response.contentType val contentLength: Option[Long] = response.contentLength ``` -------------------------------- ### Initialize Prometheus Backend with Default Settings Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/prometheus.html Wrap an existing backend with PrometheusBackend to enable default metrics collection for request durations and active requests. ```scala import sttp.client4.pekkohttp.* val backend = PrometheusBackend(PekkoHttpBackend()) ``` -------------------------------- ### Create a default HttpClientFutureBackend Source: https://sttp.softwaremill.com/en/stable/backends/future.html Instantiate the HttpClientFutureBackend with default settings. ```scala val backend = HttpClientFutureBackend() ``` -------------------------------- ### Create OkHttp Monix Backend Source: https://sttp.softwaremill.com/en/stable/backends/monix.html Create an asynchronous Monix-based backend using OkHttp. The backend is returned as a Task, requiring manual closing if not wrapped in a Resource. ```scala import sttp.client4.okhttp.monix.OkHttpMonixBackend OkHttpMonixBackend().flatMap { backend => ??? } ``` ```scala // or, if you'd like the backend to be wrapped in cats-effect Resource: OkHttpMonixBackend.resource().use { backend => ??? } ``` ```scala // or, if you'd like to instantiate the OkHttpClient yourself: import okhttp3._ val okHttpClient: OkHttpClient = ??? val backend = OkHttpMonixBackend.usingClient(okHttpClient) ``` -------------------------------- ### Create ArmeriaCatsBackend with Custom WebClient Source: https://sttp.softwaremill.com/en/stable/backends/catseffect.html Instantiate ArmeriaCatsBackend using a custom Armeria WebClient, potentially with decorators. ```scala import cats.effect.IO import com.linecorp.armeria.client.WebClient import com.linecorp.armeria.client.circuitbreaker._ import sttp.client4.armeria.cats.ArmeriaCatsBackend // Fluently build Armeria WebClient with built-in decorators val client = WebClient.builder("https://my-service.com") // Open circuit on 5xx server error status .decorator(CircuitBreakerClient.newDecorator(CircuitBreaker.ofDefaultName(), CircuitBreakerRule.onServerErrorStatus())) .build() val backend = ArmeriaCatsBackend.usingClient[IO](client) ``` -------------------------------- ### Generate sttp-client code with openapi-generator CLI Source: https://sttp.softwaremill.com/en/stable/other/openapi.html Use the openapi-generator-cli to generate Scala sttp4 client code from a petstore.yaml specification. This is a standalone setup. ```bash openapi-generator-cli generate \ -i petstore.yaml \ --generator-name scala-sttp4-jsoniter \ -o samples/client/petstore/ ``` -------------------------------- ### Consuming WebSocket Streams with WebSocketStreamConsumer Source: https://sttp.softwaremill.com/en/stable/testing/stub.html When using asWebSocketStream, provide behavior using WebSocketStreamConsumer. This example shows how to set up a backend to adjust responses with a WebSocketStreamConsumer. ```scala import cats.effect.IO import sttp.capabilities.fs2.Fs2Streams import sttp.client4.WebSocketStreamBackend import sttp.client4.httpclient.fs2.HttpClientFs2Backend import sttp.client4.testing.WebSocketStreamConsumer import sttp.client4.ws.stream._ val backend: WebSocketStreamBackend[IO, Fs2Streams[IO]] = HttpClientFs2Backend .stub[IO] .whenAnyRequest .thenRespondAdjust( WebSocketStreamConsumer[IO](Fs2Streams[IO]) { pipe => // somehow consume the pipe: fs2.Pipe[IO, WebSocketFrame.Data, WebSocketFrame] to produce an IO[Unit] ??? }) basicRequest .get(uri"http://example.org") .response(asWebSocketStream(Fs2Streams[IO]) { // the client-side behavior, a fs2.Pipe[IO, WebSocketFrame.Data, WebSocketFrame] ??? }) .send(backend) ``` -------------------------------- ### Create FetchMonixBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/javascript/fetch.html Instantiate the `FetchMonixBackend` for Scala.js. This backend is used when working with Monix. ```scala val backend = FetchMonixBackend() ``` -------------------------------- ### Create ArmeriaFutureBackend with a custom WebClient Source: https://sttp.softwaremill.com/en/stable/backends/future.html Create an ArmeriaFutureBackend by providing a custom configured Armeria WebClient. ```scala import com.linecorp.armeria.client.circuitbreaker.* import com.linecorp.armeria.client.WebClient // Fluently build Armeria WebClient with built-in decorators val client = WebClient.builder("https://my-service.com") // Open circuit on 5xx server error status .decorator(CircuitBreakerClient.newDecorator(CircuitBreaker.ofDefaultName(), CircuitBreakerRule.onServerErrorStatus())) .build() val backend = ArmeriaFutureBackend.usingClient(client) ``` -------------------------------- ### Request and Response Payload Case Classes Source: https://sttp.softwaremill.com/en/stable/other/json.html Defines simple case classes for representing JSON payloads for both requests and responses. These are used in subsequent examples. ```scala case class RequestPayload(data: String) case class ResponsePayload(data: String) ``` -------------------------------- ### Create ArmeriaCatsBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/catseffect.html Create an instance of ArmeriaCatsBackend using the default client factory. ```scala import cats.effect.IO import sttp.client4.armeria.cats.ArmeriaCatsBackend val backend = ArmeriaCatsBackend[IO]() // You can use the default client which reuses the connection pool of ClientFactory.ofDefault() ArmeriaCatsBackend.usingDefaultClient[IO]() ``` -------------------------------- ### Create ArmeriaZioBackend with Custom WebClient Source: https://sttp.softwaremill.com/en/stable/backends/zio.html Instantiate the ArmeriaZioBackend using a custom, fluently-built Armeria WebClient with decorators like circuit breakers. ```scala import com.linecorp.armeria.client.circuitbreaker.* import com.linecorp.armeria.client.WebClient import sttp.client4.armeria.zio.ArmeriaZioBackend // Fluently build Armeria WebClient with built-in decorators val client = WebClient.builder("https://my-service.com") // Open circuit on 5xx server error status .decorator(CircuitBreakerClient.newDecorator(CircuitBreaker.ofDefaultName(), CircuitBreakerRule.onServerErrorStatus())) .build() ArmeriaZioBackend.usingClient(client).flatMap { backend => ??? ``` -------------------------------- ### Define and Customize a Basic Request Source: https://sttp.softwaremill.com/en/stable/requests/basics.html Demonstrates creating a request, adding a cookie, setting a string body, and specifying a POST request to a URI. Request parameters can be specified in any order. ```scala val request = basicRequest .cookie("login", "me") .body("This is a test") .post(uri"http://endpoint.com/secret") ``` -------------------------------- ### Stubbing File Response (Copy and Adjust) Source: https://sttp.softwaremill.com/en/stable/testing/stub.html To have a file written to a destination, use `.thenRespondF` with `FileUtils.copyFile` and `ResponseStub.adjust`. This example uses Cats Effect IO for asynchronous operations. ```scala import org.apache.commons.io.FileUtils import cats.effect.* import sttp.client4.impl.cats.implicits.* import sttp.monad.MonadAsyncError val sourceFile = new File("path/to/file.ext") val destinationFile = new File("path/to/file.ext") BackendStub(implicitly[MonadAsyncError[IO]]) .whenRequestMatches(_ => true) .thenRespondF: _ => FileUtils.copyFile(sourceFile, destinationFile) IO(ResponseStub.adjust(destinationFile, StatusCode.Ok)) ``` -------------------------------- ### Create Armeria FS2 Backend with Custom WebClient Source: https://sttp.softwaremill.com/en/stable/backends/fs2.html Create an Armeria FS2 backend using a custom-instantiated Armeria WebClient, potentially with decorators. ```scala import cats.effect.IO import cats.effect.std.Dispatcher import com.linecorp.armeria.client.WebClient import com.linecorp.armeria.client.circuitbreaker.* import sttp.client4.armeria.fs2.ArmeriaFs2Backend val dispatcher: Dispatcher[IO] = ??? // Fluently build Armeria WebClient with built-in decorators val client = WebClient.builder("https://my-service.com") // Open circuit on 5xx server error status .decorator(CircuitBreakerClient.newDecorator(CircuitBreaker.ofDefaultName(), CircuitBreakerRule.onServerErrorStatus())) .build() val backend = ArmeriaFs2Backend.usingClient[IO](client, dispatcher) ``` -------------------------------- ### Custom Backend Wrapper with Redirects Disabled Source: https://sttp.softwaremill.com/en/stable/conf/redirects.html Example of a custom backend wrapper that disables `FollowRedirectsBackend` instances further down the delegate chain. This ensures only the top-level redirect handler is active. ```scala import sttp.capabilities.Effect import sttp.client4.* import sttp.client4.wrappers.FollowRedirectsBackend import sttp.monad.MonadError abstract class MyWrapper[F[_], P] private (delegate: GenericBackend[F, P]) extends GenericBackend[F, P]: def send[T](request: GenericRequest[T, P with Effect[F]]): F[Response[T]] = ??? def close(): F[Unit] = ??? def monad: MonadError[F] = ??? object MyWrapper: def apply[F[_]](delegate: Backend[F]): Backend[F] = // disables any other FollowRedirectsBackend-s further down the delegate chain FollowRedirectsBackend(new MyWrapper(delegate) with Backend[F] {}) ``` -------------------------------- ### Parse Response Stream to Server-Sent Events Source: https://sttp.softwaremill.com/en/stable/backends/monix.html This example demonstrates parsing a received Observable stream into a stream of Server-Sent Events. It uses `MonixServerSentEvents.parse` to transform the raw byte stream. ```scala import monix.reactive.Observable import monix.eval.Task import sttp.capabilities.monix.MonixStreams import sttp.client4.impl.monix.MonixServerSentEvents import sttp.model.sse.ServerSentEvent import sttp.client4.* def processEvents(source: Observable[ServerSentEvent]): Task[Unit] = ??? basicRequest.response(asStream(MonixStreams)(stream => processEvents(stream.transform(MonixServerSentEvents.parse)))) ``` -------------------------------- ### Create FetchBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/javascript/fetch.html Instantiate the default `FetchBackend` for Scala.js. Timeouts are managed using `AbortController`. ```scala val backend = FetchBackend() ``` -------------------------------- ### Registering a Request Body Progress Callback Source: https://sttp.softwaremill.com/en/stable/other/body_callbacks.html Example of setting up and using a BodyProgressCallback to track the progress of sending a file as a request body. The callback logs initialization, data chunks, completion, or errors. ```scala import sttp.client4.* import sttp.client4.httpclient.{HttpClientSyncBackend, BodyProgressCallback} import java.io.File val backend = HttpClientSyncBackend() val fileToSend: File = ??? val callback = new BodyProgressCallback { override def onInit(contentLength: Option[Long]): Unit = println(s"expected content length: $contentLength") override def onNext(bytesCount: Long): Unit = println(s"next, bytes: $bytesCount") override def onComplete(): Unit = println(s"complete") override def onError(t: Throwable): Unit = println(s"error: ${t.getMessage}") } val response = basicRequest .get(uri"http://example.com") .body(fileToSend) .attribute(BodyProgressCallback.RequestAttribute, callback) .send(backend) ``` -------------------------------- ### Create HttpClientSyncBackend with Custom Client Source: https://sttp.softwaremill.com/en/stable/backends/synchronous.html Create a synchronous backend using a pre-instantiated Java HttpClient. ```scala import sttp.client4.httpclient.HttpClientSyncBackend import java.net.http.HttpClient val httpClient: HttpClient = ??? val backend = HttpClientSyncBackend.usingClient(httpClient) ``` -------------------------------- ### Configure Custom Request Duration Histogram Name Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/prometheus.html Customize the histogram name for tracking request durations by providing a mapper function. This example uses the request's host as the histogram name. ```scala import sttp.client4.pekkohttp.* val backend = PrometheusBackend( PekkoHttpBackend(), PrometheusConfig( requestToHistogramNameMapper = request => Some(HistogramCollectorConfig(request.uri.host.getOrElse("example.com"))) ) ) ``` -------------------------------- ### Instantiate Finagle Backend Source: https://sttp.softwaremill.com/en/stable/backends/finagle.html Import and instantiate the FinagleBackend to handle asynchronous HTTP requests. ```scala import sttp.client4.finagle.FinagleBackend val backend = FinagleBackend() ``` -------------------------------- ### Create PekkoHttpBackend with Existing Actor System Source: https://sttp.softwaremill.com/en/stable/backends/pekko.html Create a PekkoHttpBackend instance using an existing pekko ActorSystem, useful for integrating with existing pekko applications. ```scala import sttp.client4.pekkohttp.* import org.apache.pekko.actor.ActorSystem val actorSystem: ActorSystem = ??? val backend = PekkoHttpBackend.usingActorSystem(actorSystem) ``` -------------------------------- ### Serialize and Deserialize JSON with uPickle Source: https://sttp.softwaremill.com/en/stable/quickstart.html Example demonstrating how to send a JSON request body and parse a JSON response body using the uPickle library. The response body can indicate HTTP or deserialization errors. ```scala //> using dep com.softwaremill.sttp.client4::core:4.0.25 //> using dep com.softwaremill.sttp.client4::upickle:4.0.25 import sttp.client4.* import sttp.client4.upicklejson.default.* import upickle.default.* @main def run(): Unit = val backend = DefaultSyncBackend() case class MyRequest(field1: String, field2: Int) // selected fields from the JSON that is being returned by httpbin case class HttpBinResponse(origin: String, headers: Map[String, String]) given ReadWriter[MyRequest] = macroRW[MyRequest] given ReadWriter[HttpBinResponse] = macroRW[HttpBinResponse] val request = basicRequest .post(uri"https://httpbin.org/post") .body(asJson(MyRequest("test", 42))) .response(asJson[HttpBinResponse]) val response = request.send(backend) response.body match { case Left(e) => println(s"Got response exception:\n$e") case Right(r) => println(s"Origin's ip: ${r.origin}, header count: ${r.headers.size}") } ``` -------------------------------- ### Configure Custom In-Progress Request Gauge Name Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/prometheus.html Customize the gauge name for tracking currently in-progress requests by providing a mapper function. This example uses the request's host as the gauge name. ```scala import sttp.client4.pekkohttp.* val backend = PrometheusBackend( PekkoHttpBackend(), PrometheusConfig( requestToInProgressGaugeNameMapper = request => Some(CollectorConfig(request.uri.host.getOrElse("example.com"))) ) ) ``` -------------------------------- ### Create AkkaHttpBackend with Existing ActorSystem Source: https://sttp.softwaremill.com/en/stable/backends/akka.html Instantiate the Akka HTTP backend using an existing ActorSystem. ```scala import sttp.client4.akkahttp._ import akka.actor.ActorSystem val actorSystem: ActorSystem = ??? val backend = AkkaHttpBackend.usingActorSystem(actorSystem) ``` -------------------------------- ### Create Armeria FS2 Backend Resource Source: https://sttp.softwaremill.com/en/stable/backends/fs2.html Create an Armeria FS2 backend using a cats-effect Resource. ```scala import cats.effect.IO import cats.effect.std.Dispatcher import sttp.client4.armeria.fs2.ArmeriaFs2Backend ArmeriaFs2Backend.resource[IO]().use { backend => ??? } ``` -------------------------------- ### Create Armeria Scalaz Backend with Custom WebClient Source: https://sttp.softwaremill.com/en/stable/backends/scalaz.html Create a custom Armeria WebClient with decorators and then use it to instantiate the Armeria Scalaz backend. This allows for advanced configuration like circuit breakers. ```scala import com.linecorp.armeria.client.circuitbreaker._ import com.linecorp.armeria.client.WebClient // Fluently build Armeria WebClient with built-in decorators val client = WebClient.builder("https://my-service.com") // Open circuit on 5xx server error status .decorator(CircuitBreakerClient.newDecorator(CircuitBreaker.ofDefaultName(), CircuitBreakerRule.onServerErrorStatus())) .build() val backend = ArmeriaScalazBackend.usingClient(client) ``` -------------------------------- ### Create HttpURLConnectionBackend Source: https://sttp.softwaremill.com/en/stable/backends/synchronous.html Instantiate the synchronous backend using HttpURLConnection. ```scala import sttp.client4.httpurlconnection.HttpURLConnectionBackend val backend = HttpURLConnectionBackend() ``` -------------------------------- ### Configure HTTP Proxy with BackendOptions Source: https://sttp.softwaremill.com/en/stable/conf/proxy.html Manually specify HTTP proxy settings when creating a backend. This is useful when system properties are not sufficient or need to be overridden. ```scala import sttp.client4.* val backend = DefaultSyncBackend( options = BackendOptions.httpProxy("some.host", 8080)) basicRequest .get(uri"...") .send(backend) // uses the proxy ``` -------------------------------- ### Instantiate Otel4sMetricsBackend Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/opentelemetry.html Use Otel4sMetricsBackend to enable tracing of a client, requiring a MeterProvider and a cats-effect backend. ```scala import cats.effect.* import org.typelevel.otel4s.metrics.MeterProvider import sttp.client4.* import sttp.client4.opentelemetry.otel4s.* implicit val meterProvider: MeterProvider[IO] = ??? val catsBackend: Backend[IO] = ??? Otel4sMetricsBackend(catsBackend, Otel4sMetricsConfig.default) .use { backend => ??? } ``` -------------------------------- ### Request with Header using Traits Source: https://sttp.softwaremill.com/en/stable/model/model.html Shows how to create a request using traits for header names and media types, simplifying the header definition. ```scala import sttp.client4.* import sttp.model.* object Example extends HeaderNames with MediaTypes with StatusCodes: val request = basicRequest.header(ContentType, ApplicationJson.toString) .get(uri"https://httpbin.org") val backend = DefaultSyncBackend() val response = request.send(backend) if response.code == Ok then println("Ok!") ``` -------------------------------- ### Wrap Backend with Caching Backend Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/cache.html Instantiate the CachingBackend by wrapping an existing backend and providing a cache implementation. This enables caching for eligible requests. ```scala import sttp.client4.caching.CachingBackend CachingBackend(delegateBackend, myCacheImplementation) ``` -------------------------------- ### Send a Request with a Synchronous Backend Source: https://sttp.softwaremill.com/en/stable/requests/basics.html Shows how to create a default synchronous backend and use it to send a defined request. The response is handled as a `Either[String, String]`. ```scala val backend = DefaultSyncBackend() val response: Response[Either[String, String]] = request.send(backend) ``` -------------------------------- ### Create HttpClientSyncBackend Source: https://sttp.softwaremill.com/en/stable/backends/synchronous.html Instantiate the default synchronous backend using Java's built-in HttpClient. ```scala import sttp.client4.httpclient.HttpClientSyncBackend val backend = HttpClientSyncBackend() ``` -------------------------------- ### Create Armeria FS2 Backend with Default Client Source: https://sttp.softwaremill.com/en/stable/backends/fs2.html Create an Armeria FS2 backend using the default client, which reuses the connection pool of ClientFactory.ofDefault(). ```scala import cats.effect.IO import cats.effect.std.Dispatcher import sttp.client4.armeria.fs2.ArmeriaFs2Backend val dispatcher: Dispatcher[IO] = ??? // You can use the default client which reuses the connection pool of ClientFactory.ofDefault() ArmeriaFs2Backend.usingDefaultClient[IO](dispatcher) ``` -------------------------------- ### Create FS2 Backend with Custom HttpClient Source: https://sttp.softwaremill.com/en/stable/backends/fs2.html Instantiate the HttpClient yourself and use it to create the FS2 backend. ```scala import cats.effect.IO import cats.effect.std.Dispatcher import java.net.HttpClient import sttp.client4.httpclient.fs2.HttpClientFs2Backend val httpClient: HttpClient = ??? val dispatcher: Dispatcher[IO] = ??? val backend = HttpClientFs2Backend.usingClient[IO](httpClient, dispatcher) ``` -------------------------------- ### Create Default Armeria Scalaz Backend Source: https://sttp.softwaremill.com/en/stable/backends/scalaz.html Instantiate the Armeria Scalaz backend using the default client, which reuses the connection pool from ClientFactory.ofDefault(). ```scala val backend = ArmeriaScalazBackend() // You can use the default client which reuses the connection pool of ClientFactory.ofDefault() ArmeriaScalazBackend.usingDefaultClient() ``` -------------------------------- ### Enable Host Header Override (HttpURLConnection) Source: https://sttp.softwaremill.com/en/stable/backends/synchronous.html Enable host header override for HttpURLConnectionBackend. ```bash -Dsun.net.http.allowRestrictedHeaders=true ``` -------------------------------- ### Import necessary components for OkHttpFutureBackend Source: https://sttp.softwaremill.com/en/stable/backends/future.html Import the OkHttpFutureBackend and the global ExecutionContext for asynchronous operations. ```scala import sttp.client4.okhttp.OkHttpFutureBackend import scala.concurrent.ExecutionContext.Implicits.global ``` -------------------------------- ### Import Armeria Scalaz Backend Source: https://sttp.softwaremill.com/en/stable/backends/scalaz.html Import the necessary class to utilize the Armeria Scalaz backend. ```scala import sttp.client4.armeria.scalaz.ArmeriaScalazBackend ``` -------------------------------- ### Import Prometheus Backend Source: https://sttp.softwaremill.com/en/stable/backends/wrappers/prometheus.html Import the necessary classes for the Prometheus backend. ```scala import sttp.client4.prometheus.* ``` -------------------------------- ### Initialize Curl Backend Source: https://sttp.softwaremill.com/en/stable/backends/native/curl.html Initialize the CurlBackend or CurlTryBackend for use with sttp client. ```scala import sttp.client4.curl.* val backend = CurlBackend() val tryBackend = CurlTryBackend() ``` -------------------------------- ### Create FS2 Backend with Custom Dispatcher Source: https://sttp.softwaremill.com/en/stable/backends/fs2.html Create an FS2 backend by providing a custom Dispatcher instance. ```scala import cats.effect.IO import cats.effect.std.Dispatcher import sttp.client4.httpclient.fs2.HttpClientFs2Backend val dispatcher: Dispatcher[IO] = ??? HttpClientFs2Backend[IO](dispatcher).flatMap { backend => ??? } ``` -------------------------------- ### Create Http4s Backend with Blaze Client Source: https://sttp.softwaremill.com/en/stable/backends/http4s.html Create an http4s backend using the default Blaze client builder. Ensure the http4s-blaze-client dependency is explicitly added. ```scala // the "org.http4s" %% "http4s-blaze-client" % http4sVersion dependency needs to be explicitly added Http4sBackend.usingDefaultBlazeClientBuilder[IO](): Resource[IO, StreamBackend[IO, Fs2Streams[IO]]] ``` -------------------------------- ### Add okhttp-backend dependency Source: https://sttp.softwaremill.com/en/stable/backends/future.html Include the 'okhttp-backend' dependency to use the OkHttpFutureBackend. ```scala "com.softwaremill.sttp.client4" %% "okhttp-backend" % "4.0.25" ``` -------------------------------- ### Create FetchCatsBackend Instance Source: https://sttp.softwaremill.com/en/stable/backends/javascript/fetch.html Instantiate the `FetchCatsBackend` for Scala.js, specifying the effect type (e.g., `IO`). This backend is for Cats Effect applications. ```scala val backend = FetchCatsBackend[IO]() ```