15.14. POSTing JSON Data to a Play Framework Web Service
Problem
You want to create a web service using the Play Framework that
lets users send JSON data to the service using the POST
request method.
Solution
Follow the steps from the previous recipe to create a new Play project, controller, and model.
Whereas the previous recipe used the writes
method of the Format
object in the model, this recipe uses
the reads
method. When JSON data is
received in a POST
request, the
reads
method is used to convert from
the JSON string that’s received to a Stock
object. Here’s the code for the reads
method:
def
reads
(
json
:
JsValue
)
:
JsResult
[
Stock
]
=
{
val
symbol
=
(
json
\
"symbol"
).
as
[
String
]
val
price
=
(
json
\
"price"
).
as
[
Double
]
JsSuccess
(
Stock
(
symbol
,
price
))
}
This method creates a Stock
object from the JSON value it’s given. (The complete code for the model
object is shown in the previous recipe.)
With this method added to the model, create a saveStock
method in the Application
controller:
import
play.api._
import
play.api.mvc._
object
Application
extends
Controller
{
import
play.api.libs.json.Json
def
saveStock
=
Action
{
request
=>
val
json
=
request
.
body
.
asJson
.
get
val
stock
=
json
.
as
[
Stock
]
println
(
stock
)
Ok
}
}
The saveStock
method gets the
JSON data sent to it from the request
object, and then converts it with the json.as
method. The println
statement in the method is used for
debugging purposes, and prints to the Play command line (the Play
console).
Finally, add a route that binds a POST ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.