HTTP Post Request in Scala using variables in JSON body

4.1k views Asked by At

I'm trying to make a HTTP Post request in Scala which uses a JSON body for example:

{
    "x": "hello",
    "y": "goodbye",
    "z": "hi"
}

where I'm storing "hello" and "goodbye" in variables that I am passing into the function making the request.

I can't figure out how to format the JSON body to put into the .postData part of the request. Would it be something like:

val a = "hello"
val b = "goodbye"

val request = Http(url).postData("{"x" = "${a}", "y" = "${b}", "z" = "hi"}")
    .header("content-type", "application/json")

My question is specifically how to format this part:

postData("{"x" = "${a}", "y" = "${b}", "z" = "hi"}")
1

There are 1 answers

0
Sangeeta On

Write response in the below format:

val a = "hello"
val b = "goodbye"

val responseData =
  s"""
     | {"x": ${a},
     | "y": ${b},
     | "z": "hi"
     |}""".stripMargin


val request = Http("url").postData(responseData).header("content-type", "application/json").option(HttpOptions.method("POST"))