0

I am trying to use the http4s library. I am trying to make a POST request to a REST web service with some json payload.

when I read the documentation http://http4s.org/docs/0.15/ I can only see a GET method example.

does anyone know how to make a POST?

Knows Not Much
  • 30,395
  • 60
  • 197
  • 373

3 Answers3

1

It looks like the get/getAs methods mentioned in the example are just convenience wrappers for the fetch method. See https://github.com/http4s/http4s/blob/a4b52b042338ab35d89d260e0bcb39ccec1f1947/client/src/main/scala/org/http4s/client/Client.scala#L116

Use the Request constructor and pass Method.POST as the method.

fetch(Request(Method.POST, uri))
Dylan
  • 13,645
  • 3
  • 40
  • 67
  • I found out the same thing. You maybe need to findout which implementation of Request is used and how you can modify the body to append data. – sascha10000 Jul 28 '16 at 19:02
1

https4s version: 0.14.11

The hard part is how to set the post body. When you dive into the code, you may find type EntityBody = Process[Task, ByteVector]. But wtf is it? However, if you have not been ready to dive into scalaz, just use withBody.

object Client extends App {
  val client = PooledHttp1Client()
  val httpize = Uri.uri("http://httpize.herokuapp.com")

  def post() = {
    val req = Request(method = Method.POST, uri = httpize / "post").withBody("hello")
    val task = client.expect[String](req)
    val x = task.unsafePerformSync
    println(x)
  }

  post()
  client.shutdownNow()
}

P.S. my helpful post about http4s client(Just skip the Chinese and read the scala code): http://sadhen.com/blog/2016/11/27/http4s-client-intro.html

sadhen
  • 462
  • 4
  • 14
-3
import org.http4s.circe._
import org.http4s.dsl._
import io.circe.generic.auto._      

case class Name(name: String)

  implicit val nameDecoder: EntityDecoder[Name] = jsonOf[Name]

  def routes: PartialFunction[Request, Task[Response]] = {
     case req @ POST -> Root / "hello" =>
     req.decode[Name] { name =>
     Ok(s"Hello, ${name.name}")
  }

Hope this helps.

Bharath
  • 9
  • 1
  • Isn't this server side code? in the code above you are accepting a POST request and reading a Name object from the request and then producing a response with Hello name. But my question is on the client side. – Knows Not Much Sep 22 '16 at 14:13