Introduction
It is the open-source library which provides the services for send Http requests and tackle the return responses.
It maintains the proper exception handling of request and response.So now we discuss some features of this library.
Library Dependency
For using the services of sttp client add the follwing dependency in the build.sbt of sbt project.
libraryDependencies += "com.softwaremill.sttp.client3" %% "core" % "3.3.18"
Import the given package in our code for using the sttp client.
import sttp.client3._
Implementation
The request are send from the backend which are based on Scala and Java HTTP client implementation.
They are also integrate with other Scala stacks for providing async and sync computation like Akka,zio,Htt4s etc.
Because it provide a very easy mechanism to handle all the requests and responses as it have predefined request and send methods for implementations.
Example
This is the basic sttp client example for sending a post request using the default jvm backend.
import sttp.client3._
//valid Api url
val url = uri"https://localhost:8000/person"
// Data to send in a post request
val data = Map(
"name" -> "John",
"age" -> 25,
)
//default JVM backend
val backend: SttpBackend[Identity, Any] = HttpURLConnectionBackend()
//basic request to send using jvm backend
val sttpRequest = basicRequest.body(data)
.post(url)
.send(backend)
// response return in Either form.
val sttpResponse = sttpRequest.body match {
case Right(response) = println(response)
case Left(err) => println(s"Invalid request : $err")
}
In this example there is a simple Api which is used for post request of map data which have 2 key value pair.So we to have configure the basicRequest which is provided by sttp.client3 package for arranging the simple request.
Now we have to send the post request data using the default jvm backend HttpURLConnectionBackend() or we can also use differnert other backend available like akka,zio,http4s etc
For getting the response we match the request.body which result in Either form(Right- Success,Left-Failure).
Authentication
We also use sttp for authenticating the requests by using bearer-token authentication,digest authentication.Authorisation header is added to the request by adding the proper credentials.
Basic Authentication
sttpRequest.auth.basic("username","password")
Bearer Token Authentication
val accessToken = "C78bfb142b4a03ecfa49c7f3d0f6f59ef11d8435cb644533b050d33"
sttpRequest.auth.bearer(accessToken)
Conclusion
In this blog we learn how to use sttp client for send the http requests.It has also more vast features which also provide the easy implementation of different http based projects.
References
sttp library: https://sttp.softwaremill.com/en/v2/quickstart.html