1.2.3 For Loop Tutorial – API Calls

This tutorial will teach you how a For loop is created and used in a real-world example. We’ll build a pipeline that requests data from a specified API, using the HTTP GET method, then iterates over the body of an API to return only the “name” element of it. 

As you can learn from Wikipedia, an API is an application programming interface. It works as a “connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build or use such a connection or interface is called an API specification.”

The Hypertext Transfer Protocol (HTTP) works as a request-response protocol between Kaholo and API. The GET method is used to request the data.

First, if you’re not currently a Kaholo user, create a free account here, then create a new project and a new pipeline.

 

I. Connect to the API

This step allows us to get the data from the API. Find the “HTTP-Requests” plugin in the Assets panel on the left side and drag and drop it onto the canvas. Choose the method called “Send Request” and “GET”. In the URL field insert the link to the API of your choice. We used this one:

https://archive.org/metadata/TheAdventuresOfTomSawyer_201303

 

II. Iterate over the API

We need to create a loop that will iterate over the API data and return the values we specified. 

First, we need to declare the variable we’ll use as the iterator. Go to the Code tab and define the fileIndex variable:

let fileIndex = 0;

Next, find the “CommandLine” plugin in the Assets panel on the left side and drag and drop it onto the canvas. Choose the method called “execute command” and switch the Code toggle on. Then add the code below in the “Command” field of the Action.

`echo '${actions.httprequests1.result.body.files[fileIndex].name}' `

This code tells the console to print out a specific value from the result of the previous API action, which is the “name” in this case.

 

III. Create the  Loop

To create a loop drag a line from the exit point of an Action to the entry point of the Action itself.

 

IV. Add the Conditional Code

Go to the “Advanced” tab of the CommandLine plugin. In the “Conditional Code” field of action insert the code below:

fileIndex < actions.httprequests1.result.body.files.length

This conditional code executes the Action only if the value of the fileIndex is lower than the value of the actions.httprequests1.result.body.files.length

 

Next, we’ll increment our iterator variable. By defining the Post-Execution Function, the fileIndex will be incremented by 1 after each loop iteration.