How to check if optional parameter is not set as part of "FormUrlEncoded Data" request


#1

Hi Everyone,

Please find below query that I have;

  • Scala/Play/Akka Application
  • A Vendor Systems sends me both mandatory and optional data fields.
  • For optional data fields, I want to set a default value for my declared variables incase the optional parameters have not been sent by the Vendor System.
    i. How can I check if a parameter is not sent as part of the request?

Below code gives a runtime error when the given optional parameter is not sent in the request.

if (request.body.asFormUrlEncoded.get(“accountName”)(0).isEmpty != true){
strAccountSid = request.body.asFormUrlEncoded.get(“accountName”)(0)
}


#2

Hi,

Can you add the signature of your function (with type annotations) and the imports in your file? Also, which kind of runtime error do you get?

request.body.asFormUrlEncoded should usually return an Option, which should not have a get method with a String parameter. Do you perhaps use imports from play.mvc instead of play.api.mvc? The former is the Java API, if you do not use java in the project, you should use the latter, as the Scala APIs utilize Option, which makes dealing with optional fields easier.

Either way, if a parameter has not been sent, your map (from asFormUrlEncoded) should not have an entry for it. When you call get on the java map, you will get null back in that case. (not 100% sure about that, because Play documentation is sparse). So when you get the first element with (0), this will cause a NullPointer exception. So your check should look like

if (request.body.asFormUrlEncoded.containsKey(“accountName”)) { ...`

If you want to assign a default value anyway, you can also use an easier solution, if you switch to the scala API: Scala’s map.get returns an Option. You can then use map to get the first element, if it is present, and finally call Option’s getOrElse, which let’s you provide a default value.


#3

Thanks so much crater2150, I followed your guidance and the issue is now resolved. Please note that am using “import play.api.mvc._”. below is sample code;

if (a.keySet.exists(_ == “ApiVersion”)){
strApiVersion = a.get(“ApiVersion”).get(0).toString()
}