4
votes

I am querying a search api and I need to add the query params in json as body to a post request.

val headers: scala.collection.immutable.Seq[HttpHeader] = scala.collection.immutable.Seq(
  RawHeader("accept", "application/json"),
  RawHeader("authorization", "xxxxxxxxxxxxxxxxxxxx"),
  RawHeader("content-type", "application/json"),
  RawHeader("x-customer-id", "123456789")
)

val formData = FormData(Map(
      "Keywords" -> "query", "Count" -> "25"
    ))

val request = HttpRequest(HttpMethods.POST, "https://api.xxx.com/services/xxx/v1/search?client_id=xxxxxx", headers, formData.toEntity)

Will using formData.toEntity send it as json in body of the post?

1
You need a "marshaller" like jackson or json4s...Ramón J Romero y Vigil

1 Answers

0
votes

I created a class for search query and serialized it and created an HttpEntity like so:

case class SearchObject(keyWords: String, count: Int)

val reqHeaders: scala.collection.immutable.Seq[HttpHeader] = scala.collection.immutable.Seq(
  RawHeader("accept", "application/json"),
  RawHeader("authorization", "xxxxxxxxxxxxxxxxxxxx"),
  RawHeader("content-type", "application/json"),
  RawHeader("x-customer-id", "123456789")
)

val searchObject = net.liftweb.json.Serialization.write(req) //req is search object
val searchObjectEntity = HttpEntity(ContentTypes.`application/json`, searchObject)
val request = HttpRequest(HttpMethods.POST, "https://api.xxxxxxxx.com/services/xxxxxx/v1/search?client_id=45854689", reqHeaders, searchObjectEntity)