Search code examples
scalarestliftpost-parameter

How to extract POST parameters in API - Lift framework


Hi I am using the following for my api in Lift:

case "api" :: "all" :: _ Get req => for {
    val after <- req.param("after")
    val before <- req.param("before")
    val limit <- req.param("limit")
} yield JsonResponse(json(ResponseLimitAfterBefore(limit.toInt,
                                                   after.toString,
                                                   before.toString)))

My issue is if any of the three parameters are missing it gives an error. Can anyone help me with how to assign a value to any of them if any parameter is missing? For example if after is not in the url then how can I assign a default value to after?

Thanks, -Faran


Solution

  • If seems you do not understand how for comprehensions work within Scala. Consider the following:

    scala> val x: Option[String] = Some("X")
    x: Option[String] = Some(X)
    
    scala> val y: Option[String] = None
    y: Option[String] = None
    
    scala> for(xx <- x; yy <- y) yield yy
    res0: Option[String] = None
    
    scala> for(yy <- y; xx <- x) yield xx
    res1: Option[String] = None
    

    Notice that even though xx has a value, the result is None. Given that req.param gives you a Box[String] (which is similar to an Option[String]), you could just do something like this (if you want a response whatever params are passed):

    JsonResponse(json(
    ResponseLimitAfterBefore(
      limit.map(_.toInt).openOr(0), 
      after.openOr("after default"), 
      before.openOr("another default")
    )))
    

    Or, if you just want to provide a default response overall, rather than a paramterised default response:

    (for { 
      after <- req.param("after")
      before <- req.param("before") 
      limit <- req.param("limit") 
    } yield JsonResponse(json(ResponseLimitAfterBefore(
      limit.toInt, after, before)))
    ) openOr BadRequestResponse()
    

    I would suggest playing with both LiftResponse subtypes more and also getting a firm grasp on what for comprehensions actually do.

    Hope that helps.