Nick S. Lubyanov
Nick S. Lubyanov

Reputation: 69

Playframework WS API response processing

I use The Play WS API from PlayFramework to communicate with external API. I need to process the received data, but don't know how. I get a response, and I want to pass it to other function like an JSON Object. How I can achieve that? Code I use you can see below. Thanks!

def getTasks = Action {
    Async {
      val promise = WS.url(getAppProperty("helpdesk.host")).withHeaders(
        "Accept" -> "application/json",
        "Authorization" -> "Basic bi5sdWJ5YW5vdjoyMDEzMDcwNDE0NDc=" ).get()
      for {
        response <- promise
      } yield Ok((response.json \\ "Tasks"))
    }
  }

Upvotes: 4

Views: 1472

Answers (2)

Mark S
Mark S

Reputation: 1453

I get a response, and I want to pass it to other function like an JSON Object.

I'm not sure I understand your question, but I'm guessing you want to transform the json you receive from the WS call prior to returning to the client, and that this transformation could take several lines of code. If this is correct, then you just need to add curly brackets around your yield statement so you can do more work on the response:

def getTasks = Action {
  Async {
    val promise = WS.url(getAppProperty("helpdesk.host")).withHeaders(
      "Accept" -> "application/json",
      "Authorization" -> "Basic bi5sdWJ5YW5vdjoyMDEzMDcwNDE0NDc=" ).get()
    for {
      response <- promise
    } yield {
      // here you can have as many lines of code as you want,
      // only the result of the last line is yielded
      val transformed = someTransformation(response.json)
      Ok(transformed)
    }  
  }
}

Upvotes: 1

ndeverge
ndeverge

Reputation: 21564

I took a look at the doc, and you could try:

Async {
    WS.url(getAppProperty("helpdesk.host")).withHeaders(
        "Accept" -> "application/json",
        "Authorization" -> "Basic bi5sdWJ5YW5vdjoyMDEzMDcwNDE0NDc=" ).get().map{
        response => Ok(response.json \\ "Tasks")
    }      
}

Upvotes: 0

Related Questions