Accepted answer

Definitely use spray json. Usually you separate the data models into their own file:

import spray.json._

case class Foo(a: String, b: Int)
case class Bar(c: Long, d: String)

object FooBarJsonProtocol extends DefaultJsonProtocol{
    implicit val fooFormat = jsonFormat2(Foo)
    implicit val barFormat = jsonFormat2(Bar)

Then in the route

    import FooBarJsonProtocol._
    get {
      path("foo") {
        complete {
          listOfFoo() //with the implicit in scope this will serialize as json
    } ~ post {
      path("bar") {
        entity(as[Bar]) { bar =>  //extract json Bar from post body
          complete(bar) //serialize bar to json (or whatever processing you want to do)


Got it thanks, here is my answer

import spray.routing._
import spray.json._
import spray.httpx._
import spray.http._

case class UserLogin(username: String, password: String)

object UserLoginJsonSupport extends DefaultJsonProtocol with SprayJsonSupport {
   implicit val PortofolioFormats = jsonFormat2(UserLogin)

import UserLoginJsonSupport._

trait UserAccountsServiceAPI extends HttpService{       
    val UserAccountsServiceRouting = {
      path("api" / "userservice" ) {   
        post {
           entity(as[UserLogin]) { userLogin =>

My http request with curl app

curl -i 'http://localhost:8080/api/userservice' -X POST -H "Content-Type: application/json" -d '{"username": "admin", "password": "pwd"}'


I can't imagine why this question was down-voted -- it seems specific and well-expressed.

It is a bit hard to find, but the Spray docs cover case class extraction under Spray Routing / Advanced Topics. It would be pointless to repeat their explanation here, but basically you want to use as[Foo] to deserialize HTTP content into objects. The entity directive can be used to do this for the body of a request, as shown in this longer example of the spray-routing DSL. mapTo (used in the same example) is probably what you want to serialize an object for the response.

For JSON, it would probably be easiest to use their separate Spray-JSON library, since it plugs right into their typeclass mechanism, but I think you could with some effort marry up anything you want. Spray-JSON can handle a case class with one line of glue.

By the way, the line val bar: Bar = ??? in your sample code is going to be executed at the time the route is defined, not when a request comes in, as you presumably want. Please read the Understanding the DSL Structure section of the spray-routing docs.

Related Query

More Query from same tag