Idiomatic way to create a basic HTTP Post request with Akka HTTP

Frank Versnel picture Frank Versnel · Sep 24, 2015 · Viewed 10k times · Source

I'm trying to figure out how to create a basic HTTP POST request with the Akka HTTP library. This is what I came up with:

val formData = Await.result(Marshal(FormData(combinedParams)).to[RequestEntity], Duration.Inf)
val r = HttpRequest(POST, url, headers, formData)

The thing is that it seems a bit non-idiomatic to me. Are there other ways to create a HttpEntity from FormData? Especially the fact that I have to use Await or return a Future even though the data is readily available seems overly complex for such a simple task.

Answer

mattinbits picture mattinbits · Sep 24, 2015

You can use Marshal in a for comprehension with other Futures, such as the ones you need to send the request and unmarshall the response:

val content = for {
        request <- Marshal(formData).to[RequestEntity]
        response <- Http().singleRequest(HttpRequest(method = HttpMethods.POST, uri = s"http://example.com/test", entity = request))
        entity <- Unmarshal(response.entity).to[String]
      } yield entity