aboutsummaryrefslogtreecommitdiff
path: root/docs/examples.rst
blob: e69c466f1b956b2ff383518aba33e423d2f0651b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
.. _usage_examples:

Usage examples
==============

POST a form using the synchronous backend
-----------------------------------------

Required dependencies::

  libraryDependencies ++= List("com.softwaremill.sttp" %% "core" % "1.1.13")

Example code::

  import com.softwaremill.sttp._

  val signup = Some("yes")

  val request = sttp
    // send the body as form data (x-www-form-urlencoded)
    .body(Map("name" -> "John", "surname" -> "doe"))
    // use an optional parameter in the URI
    .post(uri"https://httpbin.org/post?signup=$signup")

  implicit val backend = HttpURLConnectionBackend()
  val response = request.send()

  println(response.body)
  println(response.headers)

GET and parse JSON using the akka-http backend and json4s
---------------------------------------------------------

Required dependencies::

  libraryDependencies ++= List(
    "com.softwaremill.sttp" %% "akka-http-backend" % "1.1.13",
    "com.softwaremill.sttp" %% "json4s" % "1.1.13"
  )

Example code::

  import com.softwaremill.sttp._
  import com.softwaremill.sttp.akkahttp._
  import com.softwaremill.sttp.json4s._

  import scala.concurrent.ExecutionContext.Implicits.global

  case class HttpBinResponse(origin: String, headers: Map[String, String])

  val request = sttp
    .get(uri"https://httpbin.org/get")
    .response(asJson[HttpBinResponse])

  implicit val backend = AkkaHttpBackend()
  val response: Future[Response[HttpBinResponse]] = request.send()

  for {
    r <- response
  } {
    println(s"Got response code: ${r.code}")
    println(r.body)
    backend.close()
  }

Test an endpoint requiring multiple parameters
----------------------------------------------

Required dependencies::

  libraryDependencies ++= List("com.softwaremill.sttp" %% "core" % "1.1.13")

Example code::

  import com.softwaremill.sttp._
  import com.softwaremill.sttp.testing._

  implicit val backend = SttpBackendStub.synchronous
    .whenRequestMatches(_.uri.paramsMap.contains("filter"))
    .thenRespond("Filtered")
    .whenRequestMatches(_.uri.path.contains("secret"))
    .thenRespond("42")

  val parameters1 = Map("filter" -> "name=mary", "sort" -> "asc")
  println(
    sttp
      .get(uri"http://example.org?search=true&$parameters1")
      .send()
      .unsafeBody)

  val parameters2 = Map("sort" -> "desc")
  println(
    sttp
      .get(uri"http://example.org/secret/read?$parameters2")
      .send()
      .unsafeBody)