How hard is it to create a json api? Can you re-use a controller action for both json and a view?

StackOverflow https://stackoverflow.com/questions/22873245

  •  28-06-2023
  •  | 
  •  

Question

Does play 2 have attributes or something if you want a controller action to say pull a record from the database, and then return the object in json format?

Could a controller action return either a view or json format based on the request header type?

Was it helpful?

Solution

Play makes it very easy to serve a JSON api with it's RESTful architecture and built in JSON library. This page of the documentation spells it out completely - http://www.playframework.com/documentation/2.2.x/ScalaJsonHttp

As far as serving different formats from the same controller action, here's an example expanding on the Play docs that would work. This uses a querystring parameter, but could just as easily be a header.

Controller action:

def listPlaces(format: String) = Action {
  // Get list of Place from Service/DAO/etc
  val places: List[Place] = Place.list

  // Serve result
  format match {
    case "JSON" => {
      val json = Json.toJson(Place.list)
      Ok(json)    
    }
    case "HTML" => {
      Ok(views.html.listPlaces(places))
    }
  }
}

Routes:

GET    /places                      controllers.Application.listPlaces(format: String)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top