如何使用Wreq在Haskell中调用多个API



我正试图用一个exercie来习惯Haskell中的wreq。基本上,我调用第一个API,它会返回ID列表,然后我想调用API,它会从ID返回对象。

我的代码看起来像这个

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

如何递归地将getAllIds的结果传递到对getOneItemFromId的调用中,以便根据ID列表获得所有项目的列表?

这是一个关于逐个打印来自外部世界的列表的工作示例。

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

当执行上述程序时,它要求输入列表,然后逐个打印

> 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

从这里,您可以修改代码以使其工作。下面我提供了一个未经测试的解决方案。(我现在无法安装依赖项(

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

相关内容

  • 没有找到相关文章

最新更新