Scala – Routing based on query parameter in Play framework

playframework-2.0scala

My web application will be triggered from an external system. It will call one request path of my app, but uses different query parameters for different kinds of requests.

One of the parameters is the "action" that defines what is to be done. The rest of the params depend on the "action".

So I can get request params like these:

action=sayHello&user=Joe
action=newUser&name=Joe&address=xxx
action=resetPassword
...

I would like to be able to encode it similarly in the routes file for play so it does the query param based routing and as much of the validation of other parameters as possible.

What I have instead is one routing for all of these possibilities with plenty of optional parameters. The action processing it starts with a big pattern match to do dispatch and parameter validation.

Googling and checking SO just popped up plenty of samples where the params are encoded in the request path somehow, so multiple paths are routed to the same action, but I would like the opposite: one path routed to different actions.

One of my colleagues said we could have one "dispatcher" action that would just redirect based on the "action" parameter. It would be a bit more structured then the current solution, but it would not eliminate the long list of optional parameters which should be selectively passed to the next action, so I hope one knows an even better solution 🙂

BTW the external system that calls my app is developed by another company and I have no influence on this design, so it's not an option to change the way how my app is triggered.

Best Answer

The single dispatcher action is probably the way to go, and you don't need to specify all of your optional parameters in the route. If action is always there then that's the only one you really need.

GET  /someRoute      controller.dispatcher(action: String)

Then in your action method you can access request.queryString to get any of the other optional parameters.

Related Topic