-
Notifications
You must be signed in to change notification settings - Fork 0
ScalaJsonRequests
A JSON request is an HTTP request using a valid JSON payload as request body. It must specify the text/json or application/json mime type in its Content-Type header.
By default an Action uses an any content body parser, which lets you retrieve the body as JSON (actually as a JsValue):
import play.libs.Json._
def sayHello = Action { request =>
request.body.asJson.map { json =>
(json \ "name").asOpt[String].map { name =>
Ok("Hello " + name)
}.getOrElse {
BadRequest("Missing parameter [name]")
}
}.getOrElse {
BadRequest("Expecting Json data")
}
}It's better (and simpler) to specify our own BodyParser to ask Play to parse the content body directly as JSON:
import play.libs.Json._
def sayHello = Action(parse.json) { request =>
(request.body \ "name").asOpt[String].map { name =>
Ok("Hello " + name)
}.getOrElse {
BadRequest("Missing parameter [name]")
}
}Note: When using a JSON body parser, the
request.bodyvalue is directly a validJsValue.
You can test it with cURL from the command line:
curl
--header "Content-type: application/json"
--request POST
--data '{"name": "Guillaume"}'
http://localhost:9000/sayHello
It replies with:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 15
Hello Guillaume
In our previous example we handle a JSON request, but we reply with a text/plain response. Let’s change that to send back a valid JSON HTTP response:
import play.libs.Json._
def sayHello = Action(parse.json) { request =>
(request.body \ "name").asOpt[String].map { name =>
Ok(toJson(
Map("status" -> "OK", "message" -> ("Hello " + name))
))
}.getOrElse {
BadRequest(toJson(
Map("status" -> "KO", "message" -> "Missing parameter [name]")
))
}
}Now it replies with:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 43
{"status":"OK","message":"Hello Guillaume"}
Sending the list of Todos with Play 2.1 and JSON is very simple:
import play.libs.Json._
def tasksAsJson() = Action {
Ok(Json.toJson(Task.all().map { t=>
(t.id.toString,t.label)
} toMap))
}Next: Working with XML
- Play Json Basics
- Json Reads/Writes/Format Combinators
- Json Transformers
- Json Macro Inception
- Handling and serving Json requests
- HTTP programming
- Asynchronous HTTP programming
- The template engine
- HTTP form submission and validation
- Working with JSON
- Working with XML
- Handling file upload
- Accessing an SQL database
- Using the Cache
- Calling WebServices
- Integrating with Akka
- Internationalization
- The application Global object
- Testing your application