Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle optional query parameters in Play framework

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?

like image 765
magicduncan Avatar asked Mar 11 '12 17:03

magicduncan


People also ask

Can query parameters be optional?

As query parameters are not a fixed part of a path, they can be optional and can have default values.

Are query params always optional?

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.

What is optional in Fastapi?

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).

Is Play Framework open source?

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.


1 Answers

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]) 
like image 199
Julien Richard-Foy Avatar answered Oct 07 '22 03:10

Julien Richard-Foy