Play WSClient, lesson 3: POST, PUT, PATCH, DELETE and where the body goes
The first two lessons of this series only read from an upstream. Lesson 1 made GET calls, and lesson 2 decoded the JSON into case classes. This one writes: POST, PUT, PATCH and DELETE through Play's WSClient. The verbs turned out to be the easy part. What I actually learned is where request bodies are handled, on both sides of my service, and that neither side appears in the routes file.
Stack as before: Play 3.0.12, Scala 2.13, Guice. The upstream is JSONPlaceholder, which accepts writes and answers as if it stored them, though nothing is persisted. Every POST gets id: 101 back. The code is commit bfa278d in zakariahere/play-wsclient-lessons.
Two models for two moments
final case class NewPost(userId: Int, title: String, body: String)
object NewPost { implicit val format: OFormat[NewPost] = Json.format[NewPost] }
final case class Post(id: Int, userId: Int, title: String, body: String)
object Post { implicit val format: OFormat[Post] = Json.format[Post] }A post that a client sends me has no id yet. A post that the upstream sends back always has one. Two types say that directly. A single Post with id: Option[Int] would push a match or a .get into every place that uses it.
The four verbs
def createPost(): Action[NewPost] = Action.async(parse.json[NewPost]) { request =>
ws.url(s"$baseUrl/posts")
.post(Json.toJson(request.body))
.map(r => toPostResult(r, CREATED)(post => Created(Json.toJson(post))))
}
def replacePost(id: Int): Action[NewPost] = Action.async(parse.json[NewPost]) { request =>
ws.url(s"$baseUrl/posts/$id")
.put(Json.toJson(request.body))
.map(r => toPostResult(r, OK)(post => Ok(Json.toJson(post))))
}PATCH sends only the field that changes, and DELETE sends no body at all. toPostResult is a small helper that checks the status and then decodes the body into a Post, the status-before-shape rule from lesson 2. It takes the expected status as a parameter because a create answers 201 Created, not 200. Hard-code OK and every successful create gets reported as a 502.
These are the real responses from the running app:
POST /write/posts -> 201 {"id":101,"userId":1,"title":"Hello","body":"From Play"}
PUT /write/posts/1 -> 200 {"id":1,"userId":1,"title":"Replaced","body":"New body"}
PUT /write/posts/101 -> 404 {"error":"No such post"}
PATCH /write/posts/1/title -> 200 {"id":1,"userId":1,"title":"Only the title","body":"quia et suscipit..."}
DELETE /write/posts/1 -> 204The PATCH response keeps the original body text and changes only the title, which is exactly the difference from PUT.
The body is not in the routes file
This was the point that changed how I read a Play controller. The route for the create is:
POST /write/posts controllers.WsWriteController.createPost()It has a method, a path and a controller call. Nothing says the body is JSON or that it should become a NewPost. The routes file only knows the path and the query string. The body type lives on the value that createPost() returns: an Action[NewPost] that carries its own BodyParser, parse.json[NewPost].
Coming from Spring, this is the inverse of what I am used to. There the body is a method parameter, @RequestBody NewPost post. In Play the router calls the method first, gets back an Action, and only then does that action read the body. I checked the order with two temporary println calls, one in the method and one inside the action block:
![Pipeline: the routes file matches POST /write/posts, the router calls createPost() which returns an Action[NewPost], the action's BodyParser parse.json[NewPost] runs, and only then the block. Console output shows both lines for a valid body and only the first line for an invalid one.](/blog/media/10f17f34fb5b474c3b4aab9ce6c3e05f8aa42c0e22006c72d05963699da92ea2.png)
createPost(), but the block never runs.A valid body printed both lines. A body of {"title":"broken"} printed only the first line and returned 400. A text/plain body returned 415 Unsupported Media Type, also before my block ran. Two consequences follow:
- Inside the block,
request.bodyis already aNewPost. There is no JSON plumbing in the action. - Code in the method but outside the
Actionblock runs on every request, including the ones that end in a 400. Request logic belongs inside the block.
One correction to something I assumed. In dev mode the default error handler returned that 400 as an HTML page even when I sent Accept: application/json. The detail text lists the failing paths (obj.userId and obj.body, both error.path.missing), but if your clients need JSON error bodies, that is a separate error-handler decision.
BodyWritable: the type decides the Content-Type
The outgoing side has its own mechanism. post is declared as post[T: BodyWritable](body: T). A BodyWritable[T] holds two things for a type: how to turn a T into bytes, and which Content-Type to send. The compiler picks the instance from the static type of the argument:
JsValuesendsapplication/json.Stringsendstext/plain.Map[String, Seq[String]]sendsapplication/x-www-form-urlencoded.
It is also a separate step from Writes. Json.toJson uses Writes[NewPost] to go from a case class to a JsValue. BodyWritable[JsValue] then goes from that JsValue to an HTTP body. The form endpoint shows the form case. It posts a Map to httpbin, which echoes what it received:
{"contentTypeSent":"application/x-www-form-urlencoded","formReceived":{"langs":["scala","java"],"name":"Zakaria"}}The experiment that made it concrete was a one-line change in createPost:
.post(Json.toJson(request.body)) // JsValue
.post(Json.stringify(Json.toJson(request.body))) // StringBoth send the same characters. The second one sends them as text/plain, so JSONPlaceholder does not parse the body and answers 201 {"id": 101} with nothing else. My endpoint then returned a 502, because toPostResult could not decode that into a Post:
{"error":"Upstream sent an unexpected shape","details":{"obj.userId":[{"msg":["error.path.missing"],"args":[]}],"obj.title":[...],"obj.body":[...]}}
That 502 is the shape validation from lesson 2 doing its job. Without it, I would have returned a 201 for a post the upstream never really accepted.
A Scala 2 inference trap on the way
The form endpoint did not compile at first. Building a Json.obj with getOrElse calls inline failed with found: Object, required: Json.JsValueWrapper.
![Code that fails: Json.obj with asOpt[String].getOrElse("?") and toOption.getOrElse(JsNull) inline, giving type mismatch found Object. Code that compiles: assign each value to a typed val first, then build Json.obj.](/blog/media/89b9d2f53a13aa6051395c21fae0afaba2f7d03188dd64118809f769efb4744c.png)
vals give getOrElse no room to widen.The signature is getOrElse[B >: A](default: => B): B. Inside Json.obj, the expected type is JsValueWrapper, so the compiler looks for a B that is a supertype of String and also fits that wrapper. No such type exists, so it widens B to Object, and there is no conversion from Object to JsValueWrapper. On a plain val there is no outer expected type and the same call infers String. Assigning each value to a typed val first fixes it and also reads better.
What I take from lesson 3
- Routes pick the
Action. The action'sBodyParserreads the body, and it rejects bad input with 400 or 415 before my code runs. BodyWritablechooses the outgoingContent-Typefrom the static type, not the content. Same bytes, different type, different request.- Pass the expected status around: a create is 201, a delete is often 204.
- PUT and DELETE are idempotent, POST is not. That will decide what can be retried safely after a timeout.
Next: error handling for real. Timeouts, connection failures, recover and recoverWith, and a typed error model so the controllers stop nesting matches inside matches.