Tulasi
Tulasi

Reputation: 79

Scala recursive api call

val identifiers = List("id1","id2","id3","id4","id5","id5","id7","id8","id9","id10")

There are 10 ids are there in the list, I need to get all the ids information using some API call either it can be a post or get method.

But here the challenge is the API which returns the id's information won't return a result if the ids are more than 3.

So I want to make an API call for all those IDs in the batch format. the batch size max is 3. Since API won't return results if the ids are more than 3.

Is there any way to achieve to make an API call in a batch of size 3?

Sample API in curl

curl --location --request POST 'https://test/search' \
--header 'Content-Type: application/json' \
--data-raw '{
    "request": {
        "filters": {
           "identifier": ["id1", "id2", "id3"]
        }
    }
}'


Upvotes: 0

Views: 171

Answers (1)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

You can use grouped to do the grouping by 2 or 3 (whatever you need) elements.

The following code shows how to group, call a method that returns a Future and receive all responses back in the form of a List.

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._

//Emulate a call that returns a Future
def apiCall(ids: List[String]): Future[String] = Future(ids.mkString("[", ",", "]"))

val ids       = List("ID1", "ID2", "ID3", "ID4", "ID5")
val subIds    = ids.grouped(2).toList
//val responses = Future.sequence(subIds.map(apiCall))
val responses = Future.traverse(subIds)(apiCall)
val all       = Await.result(responses, 2.seconds)
println(all)

This prints

List([ID1,ID2], [ID3,ID4], [ID5])

You can do a http request with variety of libraries but the simplest one (in my opinion) is scalaj-http.

The method apiCall can be implemented as following

def apiCall(ids: List[String]) = Future {
  import scalaj.http.Http
  val idsAsJsonArray = ids.map(id => "\"" + id + "\"").mkString("[", ",", "]")
  Http("https://test/search")
    .postData(s"""
      |{
      |    "request": {
      |        "filters": {
      |           "identifier": $idsAsJsonArray
      |        }
      |    }
      |}
      |""".stripMargin)
    .header("Content-Type", "application/json")
    .asString
    .body
}

Upvotes: 2

Related Questions