https://kotlinlang.org logo
#http4k
Title
# http4k
e

elect

03/18/2024, 10:42 AM
what can I use in http4k to create a body like this for a POST? >
-d '{"ref":"refs/heads/featureA","sha":"aa218f56b14c9653891f9e74264a383fa43fefbd"}'
f

fredrik.nordin

03/18/2024, 11:56 AM
This from the docs will hopefully help.
j

James Richardson

03/18/2024, 12:14 PM
Copy code
import org.http4k.core.Body
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Uri
import org.http4k.core.with
import org.http4k.format.Jackson.json
import org.http4k.format.Jackson.asJsonObject

println(Request(<http://Method.POST|Method.POST>, Uri.of("")).body("""{"ref":"refs/heads/featureA","sha":"aa218f56b14c9653891f9e74264a383fa43fefbd"}"""))

val body =  Body.json().toLens()

println(Request(<http://Method.POST|Method.POST>, Uri.of("")).with(body of mapOf("ref" to "refs/heads/featureA", "sha" to "aa218f56b14c9653891f9e74264a383fa43fefbd").asJsonObject()))
something like those two? - there are quite a few ways, just depending on how you're feeling... - you can of course make DTO types etc...
e

elect

03/18/2024, 3:35 PM
I was hoping for something out of the box and concise the only example in the docs for outgoing is getting injected by a local defined variable
your first example is exactly what I'm doing rn, James the second one I cant get to compile.. what's
.json()
exactly? This?
Copy code
import org.http4k.format.KotlinxSerialization.json
j

James Richardson

03/18/2024, 3:36 PM
i put all the imports in the example above just copy them. ( as sometimes intellij gets confused)
e

elect

03/18/2024, 3:38 PM
sorry, the import optimization or myself messed them up
fixed, now it works
👍 1
I'll write my own shorter version of that, thanks!
j

James Richardson

03/18/2024, 3:39 PM
can it be shorter? 😂
e

elect

03/18/2024, 3:41 PM
lemme try 😛
j

James Richardson

03/18/2024, 3:43 PM
or use a data class of the right shape...
Copy code
import org.http4k.format.Jackson.auto
data class RefSha(val ref: String, val sha: String)
val autoBody = Body.auto<RefSha>().toLens()
println(Request(<http://Method.POST|Method.POST>, Uri.of("")).with(autoBody of RefSha(ref="refs/heads/featureA", sha="aa218f56b14c9653891f9e74264a383fa43fefbd")))
❤️ 1
e

elect

03/18/2024, 3:44 PM
ah, that's what I wanted
👍 1
j

James Richardson

03/18/2024, 3:44 PM
all are valid ways of making the body, they just have different tradeoffs.