Add json body to http4s Request

Oleg's link mostly covers it, but here's how you'd do it for a custom request body:

import org.http4s.circe._

val body = json"""{"hello":"world"}"""
val req = Request[IO](method = Method.POST, uri = Uri.uri("/"))
  .withBody(body)
  .unsafeRunSync()

Explanation:

The parameter body on the request class is of type EntityBody[IO] which is an alias for Stream[IO, Byte]. You can't directly assign a String or Json object to it, you need to use the withBody method instead.

withBody takes an implicit EntityEncoder instance, so your comment about not wanting to use an EntityEncoder doesn't make sense - you have to use one if you don't want to create a byte stream yourself. However, the http4s library has predefined ones for a number of types, and the one for type Json lives in org.http4s.circe._. Hence the import statement.

Lastly, you need to call .unsafeRunSync() here to pull out a Request object because withBody returns an IO[Request[IO]]. The better way to handle this would of course be via chaining the result with other IO operations.


As of http4s 20.0, withEntity overwrites the existing body (which defaults to empty) with the new body. The EntityEncoder is still required, and can be found with an import of org.http4s.circe._:

import org.http4s.circe._

val body = json"""{"hello":"world"}"""

val req = Request[IO](
  method = Method.POST,
  uri = Uri.uri("/")
)
.withEntity(body)