fetching multiple records from an API block
I'm having trouble fetching multiple records from an API block. I've been working on this for weeks but it doesn't work. Anyone who can help me with this?
This is the step-by-step plan that I use, but I am unable to get it to work:
1. First, you need to create a variable (let's call it recordIndex) to keep track of the current record you're processing. Initialize it to 0.
2. In the API block, you should map the data you want to extract to a variable. If the data is an array, you can use the recordIndex to access each record. For example, if the API response is an array of tasks, you might map response.tasks[recordIndex] to a variable.
3. After the API block, add an IF block. In this block, you need to set up a condition that checks if there are more records to process. This can be done by checking if recordIndex is less than the total number of records. If the total number of records is stored in a variable (let's call it totalRecords), the condition would be recordIndex < totalRecords.
4. If the condition in the IF block is true, it means there are more records to process. You can add a "Go To" block that loops back to the API block to process the next record.
5. Don't forget to increment the recordIndex variable each time a record is processed to ensure that the next record is processed in the next iteration.
17 Replies
To fetch multiple records from an API block in Voiceflow, you can follow these steps:
1. Create a Variable: Start by creating a variable, let's call it
recordIndex
, which will keep track of the current record you're processing. You can initialize it to 0.
2. Map the Data: In the API block, you should map the data you want to extract to a variable. If the data is an array, you can use the recordIndex
to access each record. For example, if the API response is an array of tasks, you might map response.tasks[recordIndex]
to a variable.
3. Add an IF Block: After the API block, add an IF block. In this block, you need to set up a condition that checks if there are more records to process. This can be done by checking if recordIndex
is less than the total number of records. If the total number of records is stored in a variable (let's call it totalRecords
), the condition would be recordIndex < totalRecords
.
4. Loop Back if More Records: If the condition in the IF block is true, it means there are more records to process. You can add a "Go To" block that loops back to the API block to process the next record.
5. Increment the recordIndex: Don't forget to increment the recordIndex
variable each time a record is processed. This ensures that the next record is processed in the next iteration.
Remember, the API block in Voiceflow allows you to make custom API calls to connect your assistant with external APIs and data. You can select the request type (GET, POST, PUT, DELETE, PATCH), add the endpoint URL, and specify Headers, Body, and Params. Once you have successfully made an API call, you can capture the response and save it to a variable using the "Capture Response" section.
If you're still having trouble, make sure to double-check your API documentation and compare your configuration to any example requests provided. You can also re-test the API call using a tool like cURL, Postman, or Insomnia to ensure it's working correctly.Are you still having trouble?
You should be able to just store the response in one var and go from there.
Yes, that works, but the problem is that only 1 response is stored in the variable (only the 1st) and not all of them
@W. Williams (SFT)
@Stino12547 I DMed you
like-gold•17mo ago
Custom function is an option 🙂
@MikeG Do you know a video or an example that I can use as an example?
like-gold•17mo ago
There's a couple of examples that are natively given. If you go to the CMS page, click functions, create a new function, you can select an example from the dropdown (for example the get user information one is a great start point for making external HTTP requests)
subsequent-cyan•17mo ago
Hello all. I am running my Voiceflow Assistant from Postman and the first time I run, i am getting empty array [ ] when i run t ome more time, I am getting the response expected. I suspect VF is waiting for the user input on the "capture" node, Ho do I bypass that? Thanks!
I answered is in another thread
subsequent-cyan•17mo ago
yes sorry, wrong copy paste
like-gold•17mo ago
run the "launch" step first
subsequent-cyan•17mo ago
I have tried that, form postman i run the launch like this:
{"action":{"type":"launch"},"config":{"tts":false,"stripSSML":true,"stopAll":true,"excludeTypes":["block","debug","flow"]}}
I am getting again an empty array [ ] same as when I run twice the regular payload such as
{
"action": {
"type": "text",
"payload": " this is a user message"
}
}
So what is the benefit?
like-gold•17mo ago
Launch makes sure to reset the session to the beginning in the case that the session exists
subsequent-cyan•17mo ago
got it
Thanks @MikeG
@MikeG Could you help me create an API that retrieves multiple records instead of just 1 using the code from the CMS. Because it doesn't work.
Code:
export default async function main(args) {
// Extract input variables from args
const { userId } = args.inputVars;
// Validate that the required input variable is provided
if (!userId) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: userId" } }]
};
}
// Define the URL for fetching user information, incorporating the userId
const url =
https://exampleapi.com/api/v1/users/${userId}
;
// Configure the fetch request
const config = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
};
try {
// Make the API call
const response = await fetch(url, config);
// Check if the response status is OK
if (!response.ok) {
throw new Error(HTTP error! status: ${response.status}
);
}
// Extract the JSON body from the response
const responseBody = response.json;
// Validate the responseBody structure as expected
if (!responseBody || typeof responseBody !== 'object') {
throw new Error("Invalid or missing response body from the API");
}
// Example: Extract user name and email from the response
const userName = responseBody.name;
const userEmail = responseBody.email;
// Create the success return object with extracted data
return {
outputVars: { userName, userEmail },
next: { path: 'success' },
trace: [
{
type: "text",
payload: { message: User info retrieved: Name - ${userName}, Email - ${userEmail}
}
}
]
};
} catch (error) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Error: " + error.message } }]
};
}
}like-gold•17mo ago
Feel free to PM me the details. I’ll check it when I’m back home!
@MikeG Okay thanks, I sent a private message