Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Async / Await to create a reactive REST API using the Scala PlayFramework
# define a route to get local weather
GET /weather/local controllers.Weather.local
package controllers
import javax.inject.Inject
import play.api.mvc._
import play.api.libs.json.JsValue
import play.api.libs.ws._
import scala.async.Async.{async, await}
import scala.concurrent.ExecutionContext.Implicits.global
class WeatherController @Inject() (ws: WSClient) extends Controller {
/**
* Get local weather
* @return
*/
def local = Action.async {
async {
// get the client's current location
val loc = await(getLocation)
// get the weather for the location
val r = await(getWeather(loc.json))
// return it
Ok(r.json)
}
}
def getWeather(loc: JsValue) = {
// extract lattitude longitude from json
val lat = (loc \ "latitude").as[Double]
val lon = (loc \ "longitude").as[Double]
// get weather for locatio
ws.url(s"http://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon").get
}
def getLocation = {
// get location by client ip
ws.url("http://www.telize.com/geoip").get
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment