postmanpostman-collection-runner

How to increase Variable value based on the iteration being run in Postman


I have an API request that I need to run in Postman-Collection-Runner thru multiple iterations. The API request uses Variable.

How can I make this variable to automatically increase with each iteration (or maybe set the iteration value as another Variable)?


Solution

  • If I understand your question correctly, you would like to assign different values to a variable in the request in different iterations which is achievable in 2 ways.

    a) Using data files

    https://learning.getpostman.com/docs/postman/collection_runs/working_with_data_files/

    The data files could be in JSON or CSV format. Unfortunately, there is no way in Postman to tie the variable values to another variable unless you want to do it in a hacky way!

    b) Pre-request & Tests scripts

    1- Initialise the environment variable in the Pre-request Scripts like this:

    var value = pm.environment.get("var");
    
    if( !value) {
        pm.environment.set("var", 1);
    }
    

    2- Increment the variable value in Tests

    var value = pm.environment.get("var");
    
    pm.environment.set("var", value+1);
    

    This creates an environment variable and increments it after each iteration. depending on how you structure your collection you might need to consider flushing/resetting the environment variable to be ready for the next run

    It worth mentioning that Pre-request Scripts and Tests running before and after the requests respectively, so you can write any scripts that would like to run after the request in the Tests. It shouldn't be necessarily a test!