Home > front end >  Loop through Items returned from an API Call and save them in array variable
Loop through Items returned from an API Call and save them in array variable

Time:08-20

I have a a REST API that when I call with GET for example from a browser I get a proper response like:

[
{"name": "jack",
 "id" : 23
},
{"name": "joe",
 "id" : 45
},
{"name": "james",
 "id" : 56
}
]

So now in ADF I add a Web Activity and call the same API. If at all possible: I want to have those items from the response in a array variable so I can loop through them. How do I do this? I have created a Set Variable activity and connected to output of my WebAPI call like picture below enter image description here and my pipeline variable is called apiCallOutput with type of Array.

Looking in Pipeline Run, the output of the Web APICall is like this:

{
    "Response": "[
{"name": "jack",
 "id" : 23
},
{"name": "joe",
 "id" : 45
},
{"name": "james",
 "id" : 56
}
]",
    "typicalMetaData" : "stuff That Azure adds"
}

CodePudding user response:

The following is a demonstration of how you can loop through items (and use its values) from the response which is returned using Web activity.

  • The following is the data that would be returned by my sample web activity (a sample provided, there are 100 items in total). I am just retrieving just userId and title for demonstration.
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
 ]

enter image description here

  • You can directly use the Response in For Each activity. For items field in the for each activity, you can use the following dynamic content.
@json(activity('Web1').output.Response)

enter image description here

  • Now you can access the item values inside the for each loop with 2 set variable activities. (provided dynamic content for your case)
#to get name value
@string(item().name) 

#to get id value
@string(item().id)

enter image description here

Now when you debug the pipeline, you can see that the required values will be retrieved.

  • The output for value1 set variable activity.

enter image description here

  • The output for value2 set variable activity.

enter image description here

This way you can assign the item values into variables (String type) and use them inside for each directly.

NOTE:

You can directly use the values of an item as @item().name and @item().id without using set variable activity activity as well.

  • Related