How to Skip a Collection Run in Postman Based on Response Conditions

When working with Postman to automate API testing, you might encounter scenarios where you want to conditionally skip the execution of subsequent requests in a collection. This can be useful if a certain condition isn't met in your API responses. Here's a guide on how to achieve this using Postman's scripting capabilities.

Scenario

Imagine you have a collection where the first request returns a response like this:

{
    "content": "True",
    "statusCode": 200,
    "message": "Global value got from DbConfig!"
}

You want to skip all subsequent requests if the content field is "False".

Step-by-Step Guide

  1. Set Up Your Collection: Ensure your collection is organized with the request you want to evaluate placed at the beginning.

  2. Write a Post-Request Script: In the test script section of the first request, you'll write a script to check the content field and decide whether to continue the collection run.

    // Parse the response
    let response = pm.response.json();
    
    // Check the content value
    if (response.content === "False") {
        pm.execution.setNextRequest(null); // Skip the remaining requests
    }
    

    This script checks if the content is "False". If it is, pm.setNextRequest(null) stops all subsequent requests from running.

  3. Test the Flow: Run your collection to see the logic in action. If the condition is met (i.e., content is "False"), the collection run will halt after the first request.

Explanation

  • pm.response.json(): This method parses the JSON response from your request.
  • pm.setNextRequest(null): This function is used to stop further requests in the collection run. If the condition isn't met, the collection continues with all remaining requests in their original order.

Benefits

  • Efficiency: Avoid unnecessary API calls when certain conditions aren’t met, saving time and resources.
  • Control: Gain greater control over your testing workflows by dynamically determining execution paths.

Conclusion

Using pm.execution.setNextRequest(null) in a test script provides a straightforward way to control the flow of your Postman collection runs based on specific conditions in your API responses. This technique can be a powerful tool in optimizing your automated testing processes.

Feel free to customize the logic to fit your specific needs!