Lets say I have an already functioning Play 2.0 framework based application in Scala that serves a URL such as:
http://localhost:9000/birthdays
which responds with a listing of all known birthdays
I now want to enhance this by adding the ability to restrict results with optional "from" (date) and "to" request params such as
http://localhost:9000/birthdays?from=20120131&to=20120229
(dates here interpreted as yyyyMMdd)
My question is how to handle the request param binding and interpretation in Play 2.0 with Scala, especially given that both of these params should be optional.
Should these parameters be somehow expressed in the "routes" specification? Alternatively, should the responding Controller method pick apart the params from the request object somehow? Is there another way to do this?
As query parameters are not a fixed part of a path, they can be optional and can have default values.
Yes, mandatory parameters can be used in query parameters. In that case you need to put a validation after the API is hit to check whether the value of the parameter is not null and is of specified format.
Optional parameters are a bigger set that includes query parameters. That is, query parameters take an input that is a value, while optional parameters are query parameters that can have no value (i.e. None).
Play Framework is an open-source web application framework which follows the model–view–controller (MVC) architectural pattern. It is written in Scala and usable from other programming languages that are compiled to JVM bytecode, e.g. Java.
Encode your optional parameters as Option[String]
(or Option[java.util.Date]
, but you’ll have to implement your own QueryStringBindable[Date]
):
def birthdays(from: Option[String], to: Option[String]) = Action { // … }
And declare the following route:
GET /birthday controllers.Application.birthday(from: Option[String], to: Option[String])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With