Have a List in Play framework web service paramete

2020-02-07 10:31发布

问题:

I have written this web service in play framework.

controller

  def getByGenre(genre: String) = Action {
    val result = Await.result(Movies.getByGenre(genre), 5 seconds)
    Ok(toJson(result))
  }

routes

GET     /movies/genre/:genre              controllers.MoviesController.getByGenre(genre: String)

However a user may select multiple Genre. Therefore I need to convert the genre parameter to a List[String]

I also need to know how to pass that Array parameter to the web service using CURL.

回答1:

If you can pass the genres parameter as part of the query string, just repeat the parameter with different values and then retrieve it like this:

def getByGenre() = Action.async { implicit request =>
    val genres = request.queryString.get("genres")
    Movies.getByGenre(genres).map { movies =>
      Ok(toJson(movies))
    }
}

Your route will be:

GET    /movies/genre          controllers.MoviesController.getByGenre()

Also, notice that you will need to change the Movies.getByGenre signature to:

def getByGenre(genres: Option[Seq[String]]): Seq[Movies]

An final url will be something like @mfirry showed:

myhost.com/movies/genre?genre=action&genre=drama

Finally, as you may have noticed, I've removed the blocking code from you action. Using Await at your controller means that you action would be blocking for at least 5 seconds at the worst case scenario. I suggest you to take a look at the following page of Play docs:

https://www.playframework.com/documentation/2.5.x/ScalaAsync