How to use the Play WS library in a standalone Scala app
The Play WS library makes it possible to execute HTTP requests and process the response asynchronously. It provides an awesome API that is incredibly easy to use. (I’ve provided a few simple WS examples toward the end of this post.)
Prior to the release of Play 2.4 (the current 2.4 release is the M2 milestone release), it was possible to utilize the WS API in a standalone Play app, however you effectively had to bring in the entire Play Framework to use it. Ugh! This was due to a dependency on the Play core.
With the release of Play 2.4 (currently M2), this dependency no longer exists. It is now incredibly easy to utilize the WS library in any standalone Scala app.
The following steps describe how:
For the impatient, I’ve included working code in this gist on Github!
1. Add the following library dependency to build.sbt
[code language=”Scala”]
libraryDependencies ++= Seq(
"com.typesafe.play" %% "play-ws" % "2.4.0-M2"
)
[/code]
2. Initialize the WS client
[code language=”Scala”]
val config = new NingAsyncHttpClientConfigBuilder(DefaultWSClientConfig()).build
val builder = new AsyncHttpClientConfig.Builder(config)
val client = new NingWSClient(builder.build)
[/code]
Note, if using WS within the context of Play the above is not required
3. Make a request with WS. Below, are some simple examples
Be sure to provide an ExecutionContext
e.g.
[code language=”Scala”]
import scala.concurrent.ExecutionContext.Implicits.global
[/code]
POST
[code language=”Scala”]
client.url(url).post(Map("key" -> Seq("value")))
[/code]
GET
[code language=”Scala”]
client.url(url).get
[/code]
with query string
[code language=”Scala”]
client.url(url).
withQueryString("key" -> "value").
get
[/code]
with headers
[code language=”Scala”]
client.url(url).
withHeaders("Content-Type" -> "application/json").
withQueryString("key" -> "value").
get
[/code]
Note: If used within the context of play, replace client
with WS
4. Close the client
Avoid leaks! Be sure to close the client and release threads.
[code language=”Scala”]
client.close()
[/code]
Note: The above is not required if used within a Play app
Thanks!
Nice. how can I use it with testing ? if I just want to test the route ?
I have a Play project and I want to call another API from within my project. I use your sample but getting the following error:
Caused by: java.lang.NoSuchMethodError: org.jboss.netty.handler.codec.http.HttpRequest.setHeader(Ljava/lang/String;Ljava/lang/Object;)V
Any idea what am I missing?
Btw, I did not get your “Note: If used within the context of play, replace client with WS”
Thanks
Thanks , this was real helpful