DEV Community

Cover image for How to Add If/Else Branching and Flow Control to API Test Scenarios in Apidog
Hassann
Hassann

Posted on • Originally published at apidog.com

How to Add If/Else Branching and Flow Control to API Test Scenarios in Apidog

Most API tests run in a straight line: call login, call checkout, call the receipt endpoint, and assert each response. That approach breaks down when a later request depends on an earlier result. If login returns 401, running checkout adds noise and can hide the root cause. A better scenario reads the login response, branches on its result, and reports exactly where execution stopped.

Try Apidog today

This guide shows how to add if/else logic to an API test scenario in Apidog. You will build a scenario that logs in, checks the response status, and runs checkout only when login succeeds. If you need the linear scenario basics first, see how to write a test scenario with Apidog. For a language-level introduction to branching, see the MDN guide to conditional statements.

What flow control isβ€”and is not

In Apidog, automated tests are built in the Tests module. The main unit is a Test Scenario, similar to a Collection in Postman. A scenario contains Test Steps, which can be API requests or control-flow elements, such as branches, loops, and delays.

Apidog Test Scenario flow control interface

Flow control lets a scenario make decisions instead of executing every request sequentially. The Apidog flow control and conditional branching documentation covers the available controls.

This article focuses on Conditional Branching, Apidog's if/else implementation:

if login status is 200:
  run checkout
else:
  report login failure
Enter fullscreen mode Exit fullscreen mode

Do not confuse branching with looping:

  • Conditional Branching evaluates a condition and chooses a path once.
  • For Loops and ForEach Loops repeat a block of steps.

For example, use a ForEach loop to process multiple order IDs. Use a branch to decide whether a checkout request should run at all. See the ForEach loop tutorial for iteration workflows.

Apidog documentation lists no free-versus-paid restriction for flow control, branching, loops, or passing data between steps. It also does not identify a cloud-versus-self-hosted difference for these features.

Build a scenario that branches on the login response

The target workflow is simple:

  1. Send a login request.
  2. Check whether it returns HTTP 200.
  3. Run checkout only if login succeeds.
  4. Run a failure-reporting step if login fails.

Step 1: Create a test scenario

  1. Open Apidog.
  2. Go to the Tests module.
  3. Click the + next to the search bar.
  4. Create a Test Scenario.
  5. Select its directory and priority.

You now have an empty scenario ready for steps.

Step 2: Add the login request

Add a Test Step for your login endpoint. You can import an existing endpoint, use a saved endpoint case, paste cURL, or create a custom request.

For a quick implementation, create a custom POST request:

POST https://api.your-store.com/v1/login
Content-Type: application/json

{
  "email": "dana@example.com",
  "password": "correct-horse-battery-staple"
}
Enter fullscreen mode Exit fullscreen mode

Run the request once to confirm its expected response. For example:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "userId": "usr_10482"
}
Enter fullscreen mode Exit fullscreen mode

The important part for this tutorial is the HTTP status: a successful login should return 200.

Step 3: Enter orchestrate mode

Click any scenario step to open orchestrate mode.

  • The left panel shows the complete execution flow.
  • The right panel shows configuration for the selected step.
  • Drag the ≑ handle to reorder steps when needed.

You will use this view to place and configure the conditional branch.

Step 4: Add a Conditional Branching step

  1. Click Add Step.
  2. Choose Conditional Branching.
  3. Configure the condition using the login response status.

Apidog supports these judgment operators:

  • Equals
  • Does not equal
  • Exists
  • Does not exist
  • Less than
  • Less than or equal
  • Greater than
  • Greater than or equal
  • Matches with Regex
  • Contains
  • Does not contain
  • Is empty
  • Is not Empty
  • In List
  • Not in List

For this scenario, configure the branch as:

Login response status Equals 200
Enter fullscreen mode Exit fullscreen mode

Step 5: Reference the login response

Use Retrieve pre-step data to read a value from an earlier step.

  1. Click the condition value field.
  2. Click the magic wand icon.
  3. Select Retrieve pre-step data.
  4. Choose the login step.
  5. Select its response status.

Apidog uses pre-step references in this format:

{{$.<step id>.response.body.<field path>}}
Enter fullscreen mode Exit fullscreen mode

For example, to retrieve the login token from step 1:

{{$.1.response.body.token}}
Enter fullscreen mode Exit fullscreen mode

Retrieve pre-step data in Apidog

Keep these constraints in mind:

  • Retrieve pre-step data works only in the Tests module.
  • It resolves only when you run the full scenario.
  • Running a single step in isolation does not provide data from earlier scenario steps.

For this status-code condition, retrieving the prior step's status is the fastest option.

Alternative: extract a named variable

If you need to reuse a response value across multiple steps or modules, extract it into a variable.

In the login request:

  1. Open Post-processors.
  2. Add Extract Variable.
  3. Use a JSONPath expression such as:
$.token
Enter fullscreen mode Exit fullscreen mode
  1. Save it under a variable name such as token.

You can then use the token later as:

{{token}}
Enter fullscreen mode Exit fullscreen mode

This approach works in both the Tests and APIs modules. For more examples, see how to pass data between test steps.

Step 6: Add the else path

Hover over the If block and click + Else.

You now have two paths to configure:

If: login succeeded

Add the checkout request inside the If block.

If checkout requires authentication, add the login token to the request:

Authorization: Bearer {{token}}
Enter fullscreen mode Exit fullscreen mode

You can also use a pre-step response reference instead of an extracted variable. This is the same bearer-token pattern used by authenticated APIs such as those documented in the Stripe API reference.

Else: login failed

Add a step that makes the failure explicit. Options include:

  • Sending a request to a logging endpoint.
  • Sending a notification request.
  • Adding a custom request with an assertion that always fails.

The resulting workflow is:

if login status == 200:
  create checkout
else:
  report failure
Enter fullscreen mode Exit fullscreen mode

This prevents checkout from running after an invalid login response.

Step 7: Save and run the scenario

Click Save All to persist the scenario. If Apidog shows an unsaved-change dot, save before running.

Then run the full scenario:

  • Use valid credentials to verify that the If path runs.
  • Use invalid credentials to verify that the Else path runs.

Variations and advanced flow control

Branch on a response body field

You are not limited to status codes. A branch can evaluate any value you can reference.

For example, your login API might return 200 for a locked account but include account state in the body:

{
  "status": "locked",
  "token": null
}
Enter fullscreen mode Exit fullscreen mode

Reference the field:

{{$.1.response.body.status}}
Enter fullscreen mode Exit fullscreen mode

Then configure a condition such as:

status Equals "active"
Enter fullscreen mode Exit fullscreen mode

Other practical examples include:

  • Contains for a response message.
  • Greater than for a balance or stock count.
  • In List for role-based access checks.

Combine branches with loops

Branches can run inside loops.

For example, a ForEach loop can iterate over product IDs, while a Conditional Branching step skips out-of-stock products:

for each product:
  if product.stock > 0:
    process product
  else:
    skip product
Enter fullscreen mode Exit fullscreen mode

Within loop contexts, Apidog supports references such as:

{{$.<loop step id>.index}}
Enter fullscreen mode Exit fullscreen mode

The loop index starts at 0.

To access the current ForEach element:

{{$.<loop step id>.element.<field path>}}
Enter fullscreen mode Exit fullscreen mode

For a complete iteration walkthrough, see the ForEach loop tutorial.

Conditional branching and looping in Apidog

Stop a loop with Break If

Inside a loop, use Break If condition to stop iterating when a condition becomes true.

For example:

Break If response.status Equals "complete"
Enter fullscreen mode Exit fullscreen mode

You can reposition the element in the loop and add multiple break conditions where appropriate.

Configure loop error handling

Loops include an On Error element at the beginning of the loop. Its location is fixed.

Available behaviors are:

  • Ignore: continue with the next request.
  • Continue: skip the remaining requests in the current iteration.
  • Break execution: end the loop and continue after it.
  • End execution: stop the entire scenario.

Choose the behavior based on whether one failed item should fail the whole workflow.

Add a Wait step

Use the Wait element when a downstream system needs time to reflect an update.

For example:

POST /orders
Wait 1000 ms
GET /orders/{id}
Enter fullscreen mode Exit fullscreen mode

The delay is measured in milliseconds.

Use scripts for complex logic

If the built-in operators are not enough, use a pre-processor or post-processor script to calculate the result you need.

Inside scripts, do not use {{variable}} syntax directly. Instead, use:

pm.variables.get("$.2.response.body.token")
Enter fullscreen mode Exit fullscreen mode

Update the step ID and field path to match your scenario.

For related workflows, see request chaining and API test orchestration and passing data.

A scenario cannot reference the original test scenario itself. This prevents accidental infinite loops when nesting scenarios.

Automate the workflow with the Apidog CLI

A branching scenario does not need to run only in the Apidog UI. Use the Apidog CLI to execute saved scenarios in CI.

Install the CLI and authenticate:

npm install -g apidog-cli
apidog login --with-token <YOUR_ACCESS_TOKEN>
Enter fullscreen mode Exit fullscreen mode

Run a scenario by scenario ID:

apidog run --access-token $APIDOG_ACCESS_TOKEN -t <scenario_id> -e <env_id> -r cli
Enter fullscreen mode Exit fullscreen mode

Arguments:

  • -t: test scenario ID
  • -e: environment ID
  • -r: reporter

Use cli for terminal output. Use html or junit to generate pipeline artifacts:

apidog run \
  --access-token $APIDOG_ACCESS_TOKEN \
  -t <scenario_id> \
  -e <env_id> \
  -r html,cli
Enter fullscreen mode Exit fullscreen mode

The CLI resolves the branch exactly as the app does: it evaluates the login response, runs the If or Else path, and returns an exit code based on the outcome.

For setup details, see the Apidog CLI installation guide. For CI integration, see the Apidog CLI GitHub Actions guide. To run scenarios on a schedule, see how to schedule API tests in Apidog.

FAQ

What is the difference between Conditional Branching and a loop in Apidog?

Conditional Branching evaluates a condition once and chooses a path. A loop repeats a block of steps.

Use a branch for an either/or decision:

if login succeeds:
  run checkout
else:
  stop checkout
Enter fullscreen mode Exit fullscreen mode

Use a For or ForEach loop to repeat requests across a count or array. See the ForEach loop tutorial for details.

Why is Retrieve pre-step data empty?

Two common causes:

  1. It works only in the Tests module.
  2. It resolves only when you run the entire scenario.

If you run one request by itself, it has no previous scenario response to reference.

Can I branch on a response body field instead of a status code?

Yes. Use a pre-step reference such as:

{{$.1.response.body.status}}
Enter fullscreen mode Exit fullscreen mode

Or extract the value into a named variable. Then evaluate it with operators such as Equals, Contains, or In List.

For data-passing patterns, see how to pass data between test steps.

How do I use a scenario value inside a script?

Scripts do not support direct {{variable}} references. Use:

pm.variables.get("$.2.response.body.token")
Enter fullscreen mode Exit fullscreen mode

Adjust the step ID and response path for your scenario.

Does branching require a paid or self-hosted plan?

The Apidog documentation lists no plan restriction for flow control, conditional branching, loops, or passing data between steps. It also lists no cloud-versus-self-hosted distinction for these features.

Wrapping up

A linear test can tell you that something failed. A branching scenario tells you where it failed and prevents requests from running when their prerequisites are missing.

To implement this pattern:

  1. Add a login request.
  2. Add a Conditional Branching step.
  3. Read the prior response with Retrieve pre-step data or an extracted variable.
  4. Configure the If condition, such as status Equals 200.
  5. Put checkout in the If path.
  6. Put explicit failure handling in the Else path.
  7. Run the same scenario in CI with apidog run.

Try Apidog free and turn straight-line API tests into scenarios that can make decisions.

Top comments (0)