0

I'm trying to get used to wreq in Haskell with an exercice. Basically, I'm calling a first API that returns me a list of ID, and then I would like to call the API that returns the object from the ID.

My code looks like this

getAllIds :: IO ()
getAllIds = do
  r <-
    asJSON =<< get "https://dummyUrl/objectA.json" :: IO A
  let body = r ^. responseBody
  print body

getOneItemFromId :: IO ()
getOneItemFromId = do
  r <-
    asJSON =<< get "https://dummyUrl/objectB/idOfObject.json" :: IO B
  let body = r ^. responseBody
  print body

How can I pass the result of getAllIdsinto a call to getOneItemFromId recursively so that I can get a list of all the items based on the list of ID ?

Kadabra
  • 1
  • 1

1 Answers1

2

This is a working example about printing a list comming from outside world one by one.

getAllIds :: IO [Int]
getAllIds = do
  xs <- readLn :: IO [Int]
  putStrLn "This is the list of Ids"
  print xs
  return xs

printOneId :: Int -> IO ()
printOneId i = do
  putStrLn ("this is Id: " <> show i)

main = do
  xs <- getAllIds
  mapM_ printOneId xs

When executing the program above, It asks for input list and then print one by one

> echo [1,2,3] | ./main 
This is the list of Ids  -- This is the output of the program.
[1,2,3]
this is Id: 1
this is Id: 2
this is Id: 3

From here, you can modify your code to get it work. Below I provide a not-tested solution. (I can't install dependencies right now)

getAllIds :: IO [Id]
getAllIds = do
  r <-
    asJSON =<< get "https://dummyUrl/objectA.json" :: IO A
  let body = r ^. responseBody
  print body
  return body 

getOneItemFromId :: Id -> IO ()
getOneItemFromId objectId = do
  r <-
    asJSON =<< get ("https://dummyUrl/objectB/" <> show objectId <> ".json") :: IO B
  let body = r ^. responseBody
  print body

main = do 
 xs <- getAllIds 
 mapM_ getOneItemFromId xs
lsmor
  • 4,698
  • 17
  • 38