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

1

14

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

Naphthalene answered 15/11, 2013 at 22:39 Comment(0)
S
30

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) => 
      ...
    }
  }
}
Spindlelegs answered 16/11, 2013 at 6:59 Comment(10)
Thanks, this is cleaner.Naphthalene
Note that on Spray 1.2 it would be parameters('q, 'filter ? "all")Selena
@SamyDindane it doesn't matter, NameReplacable defined for strings as well as for symbolsSpindlelegs
What's the purpose of "filter" ? "all"? Could you please give an example? ThanksComyns
@KevinMeredith Read it like getOrElse for the Option type. If there's no filter parameter in the request, the value for it will be allSpindlelegs
Thanks. Also, you don't need to specify the query parameters' types? In your example, are the query parameters, q and filter assumed to be of type String since you did not specify a type?Comyns
using the latest akka 2.4.3 I get error when typing this code: too many arguments for method parameters. What has changed? Are the docs outdated?Chaplain
@Chaplain nothing, just checked and works fine, I bet you've missed some imports or the types are wrongSpindlelegs
@Spindlelegs missed what imports? Could the code sample in your solution please explicitly define the necessary imports? I have a get request working perfectly, so if there are other implicit imports I need that is news to me and not discussed at all in the docs. Thanks for the quick response.Chaplain
@Chaplain In fact you are right, this sample is wrong in that you need to provide a required value for !, like 'q ! "default", which is required. I believe this is your problemSpindlelegs

© 2022 - 2024 — McMap. All rights reserved.