WS API response processing in Playframework

I am using the Play WS API from PlayFramework to communicate with an external API. I need to process the received data, but I don’t know how to do it. I get a response, and I want to pass it to another function, such as a JSON object. How can i achieve this? The code I'm using can be seen 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")) } } 
+4
source share
2 answers

I get a response, and I want to pass it to another function, such as a JSON object.

I'm not sure I understand your question, but I assume that you want to convert the json that you receive from the WS call before it returns to the client, and that this conversion may take a few lines of code. If this is correct, you just need to add braces around the yield statement so that you can work more on the answer:

 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) } } } 
+1
source

I looked 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") } } 
0
source

Source: https://habr.com/ru/post/1490494/


All Articles