Field Notes

Play WSClient, lesson 1: your first HTTP calls

Play WSClient, lesson 1: your first HTTP calls

Most of my day is Java and Spring Boot, where outbound HTTP means a RestClient or a WebClient bean. I wanted to learn the Play Framework equivalent properly, so I am going through Play's WSClient one lesson at a time, typing every line myself in IntelliJ. This first lesson stays small: one dependency, one injected client, and three GET endpoints that call a public test API.

The code is on GitHub at zakariahere/play-wsclient-lessons. The stack is Play 3.0.12, Scala 2.13 and Guice for runtime dependency injection. The upstream is JSONPlaceholder, a free fake REST API.

One line in build.sbt

WSClient is not part of the Play core. You add it with the ws key that Play's sbt plugin exposes, next to guice:

libraryDependencies ++= Seq(guice, caffeine, ws, /* ...other deps */)

ws resolves to play-ahc-ws, the implementation backed by AsyncHttpClient on Netty. It is non-blocking, so a slow upstream occupies a socket, not a thread.

With Guice, Play binds a single shared WSClient and closes it when the application stops. You inject it, you never construct it. If you create clients by hand inside a Play app, each one has its own connection pool and threads to leak. This is the same rule as sharing one WebClient in Spring.

The controller

The controller takes the client and an ExecutionContext. The second parameter list is implicit, so Future.map can find it:

@Singleton
class WsLessonController @Inject()(ws: WSClient,
                                   val controllerComponents: ControllerComponents)
                                  (implicit ec: ExecutionContext) extends BaseController {

  private val baseUrl = "https://jsonplaceholder.typicode.com"

  def hello(): Action[AnyContent] = Action.async {
    val request: WSRequest = ws.url(s"$baseUrl/todos/1")
    request.get().map { response =>
      Ok(
        s"""Status: ${response.status} ${response.statusText}
           |Type: ${response.contentType}
           |
           |Body:
           |${response.body}""".stripMargin)
    }
  }
}

Two things here matter more than the syntax.

A WSRequest is an immutable description

ws.url(...) does not open a connection. It returns a WSRequest, and every builder method on it (addHttpHeaders, withRequestTimeout, addQueryStringParameters) returns a new request. The network call happens only at .get(), .post(...) or .execute(). So you can keep a pre-configured base request in a val and branch from it without any shared mutable state.

Pipeline: ws.url returns an immutable WSRequest, builder methods return new requests, .get() performs the I/O and returns Future[WSResponse], and .map turns it into Future[Result] for Action.async.
Everything before .get() is pure configuration. The I/O starts at .get().

Action.async, because the answer is a Future

.get() returns a Future[WSResponse], so the action must return a Future[Result]. Action.async accepts that, and Play writes the response when the future completes. No thread waits on the upstream while that happens.

Headers, a timeout and a status contract

The second endpoint is closer to a real integration. It sends an Accept header, sets a five-second timeout on this request, and decides what each upstream status means for my API:

Scala code of the todo endpoint: ws.url with Accept header and 5 second timeout, then a pattern match on response.status mapping OK to Ok(json), NOT_FOUND to NotFound and anything else to BadGateway.
An upstream 404 becomes my 404. Any other status becomes a 502, because the failure belongs to the upstream and not to my caller.

OK and NOT_FOUND are Int constants from play.api.http.Status, mixed in through BaseController. Matching on them reads better than matching on 200 and 404. The case other branch is deliberate. I do not want to pass an upstream 500 straight through as my own 500, because that tells my caller that my service is broken. BadGateway (502) says what actually happened.

The third endpoint adds query parameters. WSClient URL-encodes them for you:

def todosForUser(userId: Int): Action[AnyContent] = Action.async {
  ws.url(s"$baseUrl/todos").addQueryStringParameters(
    "userId"    -> userId.toString,
    "completed" -> "true"
  ).get().map(response => Ok(response.json))
}

And the routes:

GET  /ws/hello               controllers.WsLessonController.hello()
GET  /ws/todos/:id           controllers.WsLessonController.todo(id: Int)
GET  /ws/user/:userId/todos  controllers.WsLessonController.todosForUser(userId: Int)

What it returns

With the app running in dev mode, these are the actual responses:

GET /ws/hello
Status: 200 OK
Type: application/json; charset=utf-8

Body:
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

GET /ws/todos/5      -> 200 {"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}
GET /ws/todos/9999   -> 404 No todo with id 9999
GET /ws/user/1/todos -> 200 [{"userId":1,"id":4,"title":"et porro tempora","completed":true}, ...]

One detail surprised me. /ws/hello shows the upstream's pretty-printed JSON, but /ws/todos/5 comes back on one line. response.body is the raw string as received. response.json parses it into a JsValue, and Ok(...) serializes that value again in compact form. So Ok(response.json) is not a byte-for-byte proxy. It is a parse and a re-serialization. Usually that is what you want, because you validated it as JSON on the way. If you only need to pipe bytes through, there are cheaper options, and streaming gets its own lesson later.

What I take from lesson 1

  • Add ws, inject WSClient, never construct one yourself.
  • A WSRequest is an immutable value. The I/O happens only at .get().
  • A Future result means Action.async and an implicit ExecutionContext.
  • Map upstream statuses to your own contract instead of forwarding them as they are.

Next in the series: reading that JSON into case classes with Reads, and the difference between validate and as when the upstream sends you something you did not expect.

Keep reading