How to handle optional query parameters in Play framework
Asked Answered
E

6

75

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?

Elegist answered 11/3, 2012 at 17:29 Comment(0)
M
63

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])
Mercorr answered 11/3, 2012 at 18:45 Comment(4)
For me this wasn't enough to do routing with no parameters. I extended it to GET /birthday controllers.Application.birthday(from: Option[String] ?= None, to: Option[String] ?= None)Hospitalet
More succient: GET /birthday controllers.Application.birthday(Option[from], Option[to])Sedda
Now documented at playframework.com/documentation/2.4.x/…Deathful
Optional parameters are described here (v2.7+) => playframework.com/documentation/2.7.x/…Tilly
L
19

A maybe less clean way of doing this for java users is setting defaults:

GET  /users  controllers.Application.users(max:java.lang.Integer ?= 50, page:java.lang.Integer ?= 0)

And in the controller

public static Result users(Integer max, Integer page) {...}

One more problem, you'll have to repeat the defaults whenever you link to your page in the template

@routes.Application.users(max = 50, page = 0)
Langur answered 13/3, 2012 at 9:9 Comment(4)
Can someone confirm that (max : java.lang.Integer = null) works? 'max' always ends up null for me...Antiquarian
I fixed the answer, should have been ?=Langur
In Java you can use play.libs.F.Option instead of Scala OptionMercorr
Do you have an example of the whole thing with using the Scala or F Option. What bothers me is the repetition of the defaults in the templates. I'm always getting this suggestion to use _ for partially applied functionsLangur
Y
13

In Addition to Julien's answer. If you don't want to include it in the routes file.

You can get this attribute in the controller method using RequestHeader

String from = request().getQueryString("from");
String to = request().getQueryString("to");

This will give you the desired request parameters, plus keep your routes file clean.

Yaupon answered 12/5, 2015 at 6:4 Comment(2)
how do your router file looks? I have something like GET /url @com.mycompany.controllers.MyClass.fetchget() and it cannot find the routeImmixture
@Immixture #16301711 take a lookCantwell
D
8

Here's Julien's example rewritten in java, using F.Option: (works as of play 2.1)

import play.libs.F.Option;
public static Result birthdays(Option<String> from, Option<String> to) {
  // …
}

Route:

GET   /birthday       controllers.Application.birthday(from: play.libs.F.Option[String], to: play.libs.F.Option[String])

You can also just pick arbitrary query parameters out as strings (you have to do the type conversion yourself):

public static Result birthdays(Option<String> from, Option<String> to) {
  String blarg = request().getQueryString("blarg"); // null if not in URL
  // …
}
Duad answered 27/3, 2013 at 14:52 Comment(0)
A
5

For optional Query parameters, you can do it this way

In routes file, declare API

GET   /birthdays     controllers.Application.method(from: Long, to: Long)

You can also give some default value, in case API doesn't contain these query params it will automatically assign the default values to these params

GET   /birthdays    controllers.Application.method(from: Long ?= 0, to: Long ?= 10)

In method written inside controller Application these params will have value null if no default values assigned else default values.

Adipocere answered 9/3, 2015 at 15:10 Comment(1)
Thanks for this answer, now it shows up in swagger with a field with a default value. In my case I had a mandatory and an optional parameter.Loisloise
E
2

My way of doing this involves using a custom QueryStringBindable. This way I express parameters in routes as:

GET /birthdays/ controllers.Birthdays.getBirthdays(period: util.Period)

The code for Period looks like this.

public class Period implements QueryStringBindable<Period> {

  public static final String PATTERN = "dd.MM.yyyy";
  public Date start;

  public Date end;

  @Override
  public F.Option<Period> bind(String key, Map<String, String[]> data) {
      SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);

      try {
          start = data.containsKey("startDate")?sdf.parse(data.get("startDate")  [0]):null;
          end = data.containsKey("endDate")?sdf.parse(data.get("endDate")[0]):null;
      } catch (ParseException ignored) {
          return F.Option.None();
      }
      return F.Option.Some(this);
  }

  @Override
  public String unbind(String key) {
      SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
      return "startDate=" + sdf.format(start) + "&amp;" + "endDate=" + sdf.format(end);
  }

  @Override
  public String javascriptUnbind() {
      return null;
  }

  public void applyDateFilter(ExpressionList el) {
      if (this.start != null)
          el.ge("eventDate", this.start);
      if (this.end != null)
          el.le("eventDate", new DateTime(this.end.getTime()).plusDays(1).toDate());
  }

}

applyDateFilter is just a convienence method i use in my controllers if I want to apply date filtering to the query. Obviously you could use other date defaults here, or use some other default than null for start and end date in the bind method.

Essam answered 28/4, 2013 at 10:54 Comment(1)
Any idea how to make swagger working with this solution?Boylan

© 2022 - 2024 — McMap. All rights reserved.