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

libraryDependencies ++= Seq(
  "com.typesafe.play" %% "play-ws" % "2.4.0-M2"
)

2. Initialize the WS client

    val config = new NingAsyncHttpClientConfigBuilder(DefaultWSClientConfig()).build
    val builder = new AsyncHttpClientConfig.Builder(config)
    val client = new NingWSClient(builder.build)

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.

import scala.concurrent.ExecutionContext.Implicits.global

POST

client.url(url).post(Map("key" -> Seq("value")))

GET

client.url(url).get

with query string

client.url(url).
  withQueryString("key" -> "value").
  get

with headers

client.url(url).
  withHeaders("Content-Type" -> "application/json").
  withQueryString("key" -> "value").
  get

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.

 client.close()

Note: The above is not required if used within a Play app

Thanks!

You may also like...

3 Responses

  1. Avi says:

    Nice. how can I use it with testing ? if I just want to test the route ?

  2. masood says:

    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

  3. Tushar Maini says:

    Thanks , this was real helpful

Leave a Reply