Request Building
When you work with spray you’ll occasionally want to construct HTTP requests, e.g. when talking to an HTTP server with spray-client or when writing tests for your server-side API with spray-testkit.
For making request construction more convenient spray-httpx provides the RequestBuilding trait, that defines a simple DSL for assembling HTTP requests in a concise and readable manner.
Take a look at these examples:
import spray.httpx.RequestBuilding._
import spray.http._
import HttpMethods._
import HttpHeaders._
import ContentTypes._
// simple GET requests
Get() === HttpRequest(method = GET)
Get("/abc") === HttpRequest(method = GET, uri = "/abc")
// as second argument you can specify an object that is
// to be marshalled using the in-scope marshaller for the type
Put("/abc", "foobar") === HttpRequest(method = PUT, uri = "/abc", entity = "foobar")
implicit val intMarshaller = Marshaller.of[Int](`application/json`) {
(value, ct, ctx) => ctx.marshalTo(HttpEntity(ct, s"{ value: $value }"))
}
Post("/int", 42) === HttpRequest(method = POST, uri = "/int",
entity = HttpEntity(`application/json`, "{ value: 42 }"))
// add one or more headers by chaining in the `addHeader` modifier
Patch("/abc", "content") ~> addHeader("X-Yeah", "Naah") === HttpRequest(
method = PATCH,
uri = "/abc",
entity = "content",
headers = List(RawHeader("X-Yeah", "Naah"))
)