Play WSClient, lesson 2: from JsValue to case classes
In lesson 1 every endpoint handed back response.json, an untyped JsValue. That works for a pass-through, but as soon as I want to compute something from the payload, I want a real Scala type and a compiler that tells me when I misspell a field. This lesson turns upstream JSON into case classes with play-json, and it is mostly about one decision: as or validate.
Same stack as before: Play 3.0.12, Scala 2.13, Guice, and JSONPlaceholder as the upstream. The code for this step is commit a172383 in zakariahere/play-wsclient-lessons.
A model and a one-line codec
package models
import play.api.libs.json._
case class Todo(userId: Int, id: Int, title: String, completed: Boolean)
object Todo {
implicit val format: OFormat[Todo] = Json.format[Todo]
}Json.format is a macro. At compile time it generates a Reads[Todo] and a Writes[Todo] from the field names and types. Because the implicit lives in the companion object, any code that asks for a Reads[Todo] finds it without an import: Scala's implicit search always looks in the companion of the type being resolved. The other side of that convenience is that the JSON contract now follows the case class. Rename a field and the wire format changes too.
You also get collections for free. play-json derives Reads[Seq[Todo]] from Reads[Todo], so validating a whole list is the same call with a different type parameter.
as throws, validate returns a value
There are two ways to decode, and the endpoints use both on purpose.
// 1) The "YOLO" way
def todoAs(id: Int): Action[AnyContent] = Action.async {
ws.url(s"$baseUrl/todos/$id").get().map { response =>
val todo: Todo = response.json.as[Todo]
Ok(Json.toJson(todo.copy(title = todo.title.toUpperCase)))
}
}GET /json/as/1 returns {"userId":1,"id":1,"title":"DELECTUS AUT AUTEM","completed":false}. The upper-cased title is the proof that I worked with a Todo and not a bag of JSON. Now ask for an id that does not exist. JSONPlaceholder answers /todos/9999 with a 404 and a body of {}, and /json/as/9999 returns Play's red "Execution exception" page. The exception in it:
JsResultException(errors:List(
(/userId, List(JsonValidationError(List(error.path.missing),List()))),
(/title, List(JsonValidationError(List(error.path.missing),List()))),
(/completed, List(JsonValidationError(List(error.path.missing),List()))),
(/id, List(JsonValidationError(List(error.path.missing),List())))))Two things to note. First, play-json does not stop at the first problem: all four missing paths are reported. Second, the exception is thrown inside Future.map, so it fails the future rather than crashing a thread, and Play's error handler turns it into a 500. Nothing breaks, but my caller is told that my service failed, which is not true.
![Comparison of response.json.as[Todo], which returns a Todo or throws JsResultException and gives a Play 500 on an empty body, with response.json.validate[Todo], which returns JsSuccess or JsError that you can match on.](/blog/media/0f4b89cae99f2707e86aaa2a8033bb50b613cc5f0b6bfc594bd5c95801f01836.png)
as for JSON you produced yourself. Use validate for anything that crossed a network.Status first, then shape
The grown-up version checks the HTTP status before it looks at the body, then pattern matches on the JsResult:
def todoValidate(id: Int): Action[AnyContent] = Action.async {
ws.url(s"$baseUrl/todos/$id").get().map { response =>
response.status match {
case OK =>
response.json.validate[Todo] match {
case JsSuccess(todo, _) => Ok(Json.toJson(todo))
case e: JsError =>
BadGateway(Json.obj(
"error" -> "Upstream sent an unexpected shape",
"details" -> JsError.toJson(e)))
}
case NOT_FOUND => NotFound(Json.obj("error" -> s"No todo with id $id"))
case other => BadGateway(Json.obj("error" -> s"Upstream said $other"))
}
}
}The order is the point. If I validated first, the {} body of a missing todo would come out as "unexpected shape", a 502, when the honest answer is 404. With the status checked first, /json/todo/9999 returns 404 {"error":"No todo with id 9999"}, and a 502 is kept for the case where the upstream said 200 but sent something my model does not accept. JsError.toJson turns the accumulated errors into JSON, so the 502 body tells whoever is debugging exactly which path broke.
Validating a list works the same way. This endpoint finally answers last lesson's homework, counting a user's completed todos with real types:
response.json.validate[Seq[Todo]] match {
case JsSuccess(todos, _) =>
val done = todos.count(_.completed)
Ok(Json.obj("userId" -> userId, "total" -> todos.size,
"completed" -> done, "pending" -> (todos.size - done)))
case e: JsError => BadGateway(JsError.toJson(e))
}GET /json/user/1/stats returns {"userId":1,"total":20,"completed":11,"pending":9}.
A custom Reads: their shape in, my shape out
The macro only helps when my model mirrors the upstream. /users/1 is nested (address.city, company.name), and I do not want that nesting leaking into my domain. A hand-written Reads with the functional builder reads from nested paths into a flat case class:
case class UserSummary(name: String, email: String, city: String,
company: String, website: Option[String])
object UserSummary {
implicit val reads: Reads[UserSummary] = (
(__ \ "name").read[String] and
(__ \ "email").read[String](Reads.email) and
(__ \ "address" \ "city").read[String] and
(__ \ "company" \ "name").read[String] and
(__ \ "website").readNullable[String]
)(UserSummary.apply _)
implicit val writes: OWrites[UserSummary] = Json.writes[UserSummary]
}![Left: the nested upstream JSON for user 1 with address and company objects. Right: the Reads[UserSummary] combinator code and the flat JSON returned by GET /json/user/1.](/blog/media/c7f4a2f9ecd52875e39caacf09b6d4ef602bf198aaef1dfe983b6f803be6ec69.png)
Reads is the only place that knows the upstream is nested. Everything after it sees a flat UserSummary.__ is the JSON root and \ walks one key down. .read[String](Reads.email) adds validation on top of the type check, so a malformed email is a JsError, not a String. readNullable maps both a missing field and an explicit null to None. On the way out, Json.writes omits None fields entirely instead of writing null, which is worth knowing before a client starts relying on the key being present.
Reads and Writes do not have to be symmetric. Here the reads follow the upstream and the writes follow my API. That is the mechanism that keeps an integration change from becoming an API change.
One note for compile-time DI
At work my Play apps use compile-time dependency injection rather than Guice. Nothing in this lesson changes for that: models and codecs are plain values with no wiring. Only the controller line moves into the components class, where AhcWSComponents provides the shared client:
lazy val wsJsonController =
new WsJsonController(wsClient, controllerComponents)(executionContext)What I take from lesson 2
- Put codecs in the companion object; implicit scope finds them without imports.
asthrows,validatereturns aJsResult. Across a network boundary, a bad payload is data, not an exception.- Check the HTTP status before the shape, or a 404 turns into a misleading 502.
- play-json accumulates every failing path, and
JsError.toJsonmakes that debuggable. - A hand-written
Readskeeps the upstream's structure out of your domain.
Next: sending data the other way. POST, PUT, PATCH and DELETE, JSON and form bodies, and what BodyWritable is doing when you pass a JsValue to .post.