API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Testing APIs
  • Introduction
  • Table of Contents
  • API Academy
    • Get Started
      • What is an API?
      • How Does an API Work?
      • How to Call an API?
      • How to Read an API Documentation?
      • Chapter Summary
      • Get realtime weather
    • API Fundamentals
      • API Funtamentals: Overview
      • Method & Path
      • Parameters
      • Request Body
      • Responses
      • API Specification & OAS
      • Chapter Summary
    • Working with APIs
      • Working with APIs: Overview
      • Making Requests from Spec
      • Environments and Variables
      • Chaining Multiple Endpoints
      • Handling Authentication
      • Handling API Signatures
      • Introduction to Scripts
      • Chapter Summary
    • Mocking APIs
      • Mocking APIs: Overview
      • Smart Mock
      • Mock Expectations
      • Cloud Mock
      • Mock Scripts
      • Chapter Summary
    • Designing APIs
      • Designing APIs: Overview
      • Introduction to API Design
      • Creating Your First API Project
      • Analyzing Requirements and Planning Your API
      • Designing Data Models
      • Designing Endpoints
      • Using Components and Reusability
      • Setting Up Authentication
      • API Design Guidelines
      • Chapter Summary
    • Developing APIs
      • Developing APIs: Overview
      • Setup: Install Your AI Coding Assistant
      • Quick Start: From Spec to Running API in 30 Minutes
      • Understanding the Generated Code
      • Testing Your API with Apidog
      • Deployment: Put Your API Online
      • Chapter Summary
    • Testing APIs
      • Testing APIs: Overview
      • Getting Started: Your First Test Scenario
      • Integration Testing and Data Passing
      • Dynamic Values
      • Assertions and Validations
      • Flow Control: If, For, ForEach
      • Data-Driven Testing
      • Performance Testing
      • Test Reports and Analysis
      • CI/CD Integration
      • Scheduled Tasks and Automation
      • Advanced Testing Strategies
      • Chapter Summary
    • API Documentations
      • API Documentations: Overview
      • Publishing Your First API Doc
      • Customizing Documentation Appearance
      • Interactive Features for Consumers
      • Advanced Publishing Settings
      • Managing API Versions
      • Chapter Summary
    • Advanced API Technologies
      • API Technologies: Overview
      • GraphQL
      • gRPC
      • WebSocket
      • Socket.IO
      • Server-Sent Events (SSE)
      • SOAP
      • Chapter Summary
    • API Lifecycle
      • API Lifecycle: Overview
      • Stages of the API Lifecycle
      • API Governance
      • API Security Best Practices
      • Monitoring and Analytics
      • API Versioning Strategies
      • The Future of APIs
      • Chapter Summary
    • API Security
      • API Security: Overview
      • API Security Fundamentals
      • Authentication vs Authorization
      • Understanding OAuth 2.0 and OpenID Connect
      • JSON Web Tokens (JWT)
      • OWASP API Security Top 10
      • Encryption and HTTPS
      • Chapter Summary
    • API Tools
      • API Tools: Overview
      • The Evolution of API Tools
      • API Clients
      • Command Line Tools (cURL, HTTPie)
      • API Design and Documentation Tools
      • API Mocking Tools
      • API Testing Tools
      • All-in-One API Platforms
      • Chapter Summary
    • API Gateway
      • API Gateway: Overview
      • What is an API Gateway?
      • Key Features of API Gateways
      • API Gateway vs Load Balancer vs Service Mesh
      • Popular API Gateway Solutions
      • The BFF (Backend for Frontend) Pattern
      • Chapter Summary
  • Modern Pet Store
    • Pet
      • Get Pet
      • Update Pet
      • Delete Pet
      • Create Pet
      • List Pets
      • Upload Pet Image
    • User
      • Update User
      • Get User
      • Delete User
      • Login
      • Logout
      • Create User
    • Store
      • List Inventory
      • Create Order
      • Get Order
      • Delete Order
      • Callback Example
      • Pay for an Order
    • Payments
      • Pay Order
    • Chat
      • Create Chat Completion
    • Webhooks
      • Pet Adopted Event
      • New Pet Available Event
  • Schemas
    • Pet
    • Category
    • User
    • ApiResponse
    • OrderPayment
    • Tag
    • Order
    • Links-Order
    • PetCollection
    • Bank Card
    • Bank Account
    • Links
    • Error
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Testing APIs

Flow Control: If, For, ForEach

Real-world testing isn't always a straight line. Sometimes you need to skip a step if a login fails, or repeat a test 100 times, or iterate through a list of items returned by an API.
Apidog provides powerful Flow Control steps to build "smart" test scenarios that adapt and scale.

Why You Need Flow Control#

Why You Need Flow Control#

Without flow control, your test scenario is just a static list of requests (A -> B -> C). Real-world testing requires logic. You might need conditional execution ("If A fails, stop"), looping ("Run step B 50 times"), or iteration ("For every product in the list, run B"). Flow control gives you this flexibility.

1. Condition (If-Then-Else)#

The Condition step allows you to branch your test based on criteria.

How to Use#

How to Use#

In your Test Scenario, adding a condition is straightforward:
1.
Add a Condition step.
2.
Set your comparison rules (e.g., {{status_code}} equals 200).
3.
Drag and drop the test steps you want to protect inside the "If" block.
Condition Step Configuration

Example: "Safe" User Deletion#

Don't try to delete a user if you couldn't create one.
Step 1: Create User
   (Extract $.id to {{userId}})
   (Extract status code to {{createStatus}})

Step 2: Condition (If {{createStatus}} == 201)
   |--> Step 3: Delete User (uses {{userId}})
See details: Flow Control Conditions

2. For Loop (Fixed Repetition)#

The For Loop is perfect for simple repetition, like stress testing or creating bulk data. It runs the steps contained within it a fixed number of times designated by you.

How to Use#

1.
Click Add Step -> Loop.
2.
Choose For Loop.
3.
Set Loop Count: e.g., 10.
4.
Optionally set a Loop Delay (e.g., 1000ms) to avoid hitting rate limits.
For Loop Configuration
See details: For Loops

Example: Bulk Data Creation#

Need 50 users for a pagination test?
Step 1: For Loop (Count: 50)
   |--> Step 2: POST /users (Create User)
Pro Tip: Use dynamic data like {{$randomUserName}} in the POST /users body so you don't create 50 identical users.

3. ForEach Loop (Iterating Arrays)#

This is the most powerful loop type. Unlike the fixed "For Loop", the ForEach Loop iterates over a dynamic list (array) of dataβ€”usually one returned by a previous API response. It allows you to process every item in a collection individually.

How to Use#

1.
Get the List: First, have a step that returns an array (e.g., GET /pets).
In its Post-processors, extract the array to a variable {{petList}}.
2.
Add ForEach Step:
Reference Variable: petList (without curly braces).
Loop Variable Name: petItem (this represents the current item in the loop).
3.
Use the Item: Inside the loop, use {{petItem.id}}, {{petItem.name}}, etc.
ForEach Loop Configuration
See details: ForEach Loops

Example: Verify All Pets#

Check every pet in the store to ensure it has a valid photo URL.
Step 1: GET /pets/findByStatus?status=available
   (Extract $.data to {{petList}})

Step 2: ForEach Loop (List: {{petList}} -> Item: {{pet}})
   |--> Step 3: GET /pets/{{pet.id}}
   |--> Step 4: Condition (If {{pet.photoUrls}} is empty)
         |--> Step 5: Custom Script (Log warning)

4. Combining Flow Control#

The real power comes when you nest these controls.
Loop + Condition: You can iterate through a CSV of users (Loop) and check their age; IF they are over 18 (Condition), send a promo email.
Condition + Loop: First check IF the 'Get Product List' returns more than 100 items (Condition); if true, run a Loop to delete the excess items.

Real Case: Self-Healing Test Workflow#

Let's build a "Smart" workflow that brings the system to a known state.
Goal: We want to verify the GET /users/{id} endpoint.
Problem: The user might be "inactive", causing the GET to return 400.
Solution: If inactive, Reactivate them first, then GET.
Implementation:
1.
Step 1: GET /users (Get list)
Extract $.data -> {{userList}}
2.
Step 2: ForEach Loop (Input: {{userList}})
3.
Step 3 (Inside Loop): Condition (Check Status)
If {{petItem.status}} Equals active:
Run GET /users/{{petItem.id}}
Assert Status 200
Else:
Run POST /users/{{petItem.id}}/reactivate
Assert Status 200
Then Run GET /users/{{petItem.id}}
This is called Self-Healing Testsβ€”tests that fix the data before verifying it.

Key Takeaways#

Use Condition (If) to prevent errors and handle logic (e.g., skip steps if login fails).
Use For Loop for generating bulk test data or simple repetition.
Use ForEach Loop to iterate through dynamic lists from API responses.
Nest these controls to build complex, intelligent automation pipelines.

What's Next#

We can now control how our tests run. But what about the data? Hardcoding "testuser" is fine for one test, but what if you need to test with 100 different specific user accounts from a CSV file?
In the next chapter, we'll master Data-Driven Testing.
Continue with β†’ Data-Driven Testing
Modified atΒ 2025-12-25 09:53:30
Previous
Assertions and Validations
Next
Data-Driven Testing
Built with