I want to create a simple rest-service with spray. The rest service shall receive a json-body via http put. I want to pass the parsed json-string to a function for further processing.
Is there any example out there how to do this? I have not found any example how to access the body of a http put request as a parsed json object (spray-json)?
Thanks.
Here is the sample code for your reference.
import spray.http._
import spray.routing._
import spray.json.DefaultJsonProtocol
import spray.httpx.unmarshalling._
import spray.httpx.marshalling._
case class Person(fname: String, lname: String, age: Int)
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val PersonFormat = jsonFormat3(Person)
}
class TestActor extends HttpServiceActor {
import MyJsonProtocol._
import spray.httpx.SprayJsonSupport._
override def receive: Receive = runRoute(serviceRoute)
private val serviceRoute = path("test_end_point") {
put {
entity(as[Person]) { person =>
println(person)
complete(StatusCodes.OK)
}
}
}
}
I tested it using following command
curl -X PUT -H "Content-Type: application/json" --data '{ "fname": "Vishal", "lname" :"John", "age" : 32 }' localhost:9000/test_end_point