§Calling REST APIs with Play WS
Sometimes we would like to call other HTTP services from within a Play application. Play supports this via its WS (“WebService”) library, which provides a way to make asynchronous HTTP calls.
There are two important parts to using the WS API: making a request, and processing the response. We’ll discuss how to make both GET and POST HTTP requests first, and then show how to process the response from the WS library. Finally, we’ll discuss some common use cases.
Note: In Play 2.6, Play WS has been split into two, with an underlying standalone client that does not depend on Play, and a wrapper on top that uses Play specific classes. In addition, shaded versions of AsyncHttpClient and Netty are now used in Play WS to minimize library conflicts, primarily so that Play’s HTTP engine can use a different version of Netty. Please see the 2.6 migration guide for more information.
§Adding WS to project
To use WS, first add javaWs to your build.sbt file:
libraryDependencies ++= Seq(
javaWs
)§Enabling HTTP Caching in Play WS
Play WS supports HTTP caching, but requires a JSR-107 cache implementation to enable this feature. You can add ehcache:
libraryDependencies += ehcache
Or you can use another JSR-107 compatible cache such as Caffeine.
Once you have the library dependencies, then enable the HTTP cache as shown on WS Cache Configuration page.
Using an HTTP cache means savings on repeated requests to backend REST services, and is especially useful when combined with resiliency features such as stale-if-error and stale-while-revalidate.
§Making a Request
Now any controller or component that wants to use WS will have to add the following imports and then declare a dependency on the WSClient type to use dependency injection:
import javax.inject.Inject;
import play.libs.ws.*;
import play.mvc.*;
public class MyClient implements WSBodyReadables, WSBodyWritables {
private final WSClient ws;
@Inject
public MyClient(WSClient ws) {
this.ws = ws;
}
// ...
}
To build an HTTP request, you start with ws.url() to specify the URL.
WSRequest request = ws.url("http://example.com");
This returns a