12

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.

Frank Versnel
  • 373
  • 1
  • 4
  • 9

3 Answers3

18

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
mattinbits
  • 10,370
  • 1
  • 26
  • 35
6

Apparently a toEntity method was added to the FormData class at some point. So this now seems like the simplest solution to the problem:

val formData = FormData(combinedParams).toEntity
val r = HttpRequest(POST, url, headers, formData)
Frank Versnel
  • 373
  • 1
  • 4
  • 9
0

You can also use RequestBuilding:

Http().singleRequest(RequestBuilding.Post(url, formData)).flatMap(Unmarshal(_).to[String])
propi
  • 126
  • 5
  • Recently I've been noticing various [blogs for microservices in akka http](https://jaceklaskowski.gitbooks.io/spray-the-getting-started/content/spray-akka_http_client.html) that are using `RequestBuilding` but can't find official akka docs on why. Do you know the benefits to using `RequestBuilding`? – ecoe Feb 07 '19 at 20:32
  • I use it only because it is a shorter form. But yes, I didn't also find any examples in the official docs - that's weird but it works... – propi Feb 11 '19 at 13:43