How can I parse out get request parameters in spray-routing?

Kevin Colin picture Kevin Colin · Nov 15, 2013 · Viewed 12k times · Source

This is what the section of code looks like

    get{
      respondWithMediaType(MediaTypes.`application/json`){
          entity(as[HttpRequest]){
            obj => complete{


                println(obj)
                "ok"
            }
          }
      }
    }~

I can map the request to a spray.http.HttpRequest object and I can extract the uri from this object but I imagine there is an easier way to parse out the parameters in a get request than doing it manually.

For example if my get request is

 http://localhost:8080/url?id=23434&age=24

I want to be able to get id and age out of this request

Answer

4lex1v picture 4lex1v · Nov 16, 2013

Actually you can do this much much better. In routing there are two directives: parameter and parameters, I guess the difference is clear, you can also use some modifiers: ! and ?. In case of !, it means that this parameter must be provided or the request is going to be rejected and ? returns an option, so you can provide a default parameter in this case. Example:

val route: Route = {
  (path("search") & get) {
    parameter("q"!) { query =>
      ....
    }
  }
}

val route: Route = {
  (path("search") & get) {
    parameters("q"!, "filter" ? "all") { (query, filter) => 
      ...
    }
  }
}