0

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.

HashBr0wn
  • 387
  • 1
  • 11

1 Answers1

1

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(...)))
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • Thanks, using postData worked! Do you know if there is a reason why the get methods were working and the post did not and needs this extra step (I was able to pass params to get methods)? Also is there any way to make POST requests without having to pass in an explicit JSON using scalaj – HashBr0wn May 03 '20 at 00:49