Uses the marshaller for a given type to produce a completion function that is passed to its inner route. You can use it to decouple marshaller resolution from request completion.


def produce[T](marshaller: ToResponseMarshaller[T]): Directive[(T  Unit) :: HNil] 


The produce directive works in conjuction with instanceOf and spray.httpx.marshalling to convert higher-level (object) structure into some lower-level serialized “wire format”. The marshalling documentation explains this process in detail. This directive simplifies exposing types to clients via a route while providing some form of access to the current context.

produce is similar to handleWith. The main difference is with produce you must eventually call the completion function generated by produce. handleWith will automatically call complete when the handleWith function returns.


The following example uses spray-json to marshall a simple Person class to a json response. It utilizes SprayJsonSupport via the PersonJsonSupport object as the in-scope unmarshaller.

object PersonJsonSupport extends DefaultJsonProtocol with SprayJsonSupport {
   implicit val PortofolioFormats = jsonFormat2(Person)
case class Person(name: String, favoriteNumber: Int)

The findPerson takes an argument of type Person => Unit which is generated by the produce call. We can handle any logic we want in findPerson and call our completion function to complete the request.

import PersonJsonSupport._

val findPerson = (f: Person => Unit) => {

  //... some processing logic...

  //complete the request
  f(Person("Jane", 42))

val route = get {
  produce(instanceOf[Person]) { completionFunction => ctx => findPerson(completionFunction) }

Get("/") ~> route ~> check {
  mediaType === `application/json`
  responseAs[String] must contain(""""name": "Jane"""")
  responseAs[String] must contain(""""favoriteNumber": 42""")