HashBr0wn
HashBr0wn

Reputation: 467

Scalaj HTTP endpoint that requires a JSON-formatted body

I am trying to make a POST request using scalaj, but I am getting the following error

{"code":40010000,"message":"request body format is invalid"} java.lang.Exception: HTTP ERROR: 400

I am trying to access the Alpaca Broker API to make an order and my code looks like this

val response: HttpResponse[String] = Http(s"$endpoint/v2/orders").
  headers(Map(AlpacaInfo.key_header->key, AlpacaInfo.secret_header->secret)).
  params(Map("symbol"->symbol, "qty"->qty, "side"->side, "type"->`type`, "time_in_force"->time_in_force) ++ parameters).
  method("POST").asString

My GET requests work as intended I am just having trouble with POST. On an Alpaca discussion someone said it was likely because the encoding was not JSON formatted. How can I fix/change that?

P.S. I am new at making API calls so it is quite possible that this question is not very clear and I am unaware. Any help would be much appreciated.

Upvotes: 0

Views: 685

Answers (1)

Mario Galic
Mario Galic

Reputation: 48420

Instead of params try postData method like so

val body =
  s"""
     |{
     |  "symbol": "$symbol",
     |  "qty": $qty,
     |  "type": "$`type`",
     |  "time_in_force": "$time_in_force"
     |}
     |""".stripMargin


Http(...)
  .headers(...)
  .postData(body)
  .method("POST")
  .asString

Instead of using raw strings to represent JSON, you could use a proper JSON serialisation library, for example, upickle, and then body could be provided like so

import upickle.default._
case class MyModel(symbol: String, qty: Int, `type`: String, time_in_force: String)
implicit val configRW: ReadWriter[Config] = macroRW

Http(...)
  .postData(write(MyModel(...)))

Upvotes: 1

Related Questions