Search code examples
postmanpostman-collection-runnerpostman-pre-request-script

How to send query parameter values through script in postman for GET API request


I want to execute a Get request with different parameter values

eg:-

localhost:8080//employee/employee-details?sort_by={{sort_by}}&sort_order=ASC

in place of "{{sort_by}}" i want to execute with different values as employee_id, employee_name, department, salary ..etc.,


Solution

  • You can pass the parameter by collection variable(type is array)

    Collection Variables

    sortKeys : ["employee_id", "employee_name", "department", "salary"]
    sortKey  : employee_id
    

    enter image description here

    URL

    GET http://localhost:8080/employee/employee-details?sort_by={{sortKey}}
    

    Pre-script

    let sortKeys = JSON.parse(pm.collectionVariables.get("sortKeys"));
    pm.collectionVariables.set("sortKey", sortKeys.shift())
    pm.collectionVariables.set("sortKeys", JSON.stringify(sortKeys));
    if (sortKeys.length > 0){
        postman.setNextRequest("Get Employee"); // <- GET Request Name
    }
    

    Post-response :(in old version test script)

    // Expected values for the first employee ID based on the sort key
    const expectedFirstIds = {
        employee_id: 1,
        employee_name: 4,
        department: 3,
        salary: 5
    };
    
    // Get the current sort key from the collection variable
    const sortKey = pm.collectionVariables.get("sortKey");
    
    const responseJson = pm.response.json();
    // Check if the first employee ID matches the expected value
    pm.test(`The first employee ID for sort key ${sortKey} is correct`, function () {
        pm.expect(responseJson[0].employee_id).to.eql(expectedFirstIds[sortKey]);
    });
    

    Demo

    mock-server Save as mock-server.js

    const express = require('express');
    const app = express();
    const port = 8080;
    
    const employees = [
      { employee_id: 1, employee_name: 'David', department: 'HR', salary: 120000 },
      { employee_id: 2, employee_name: 'Eve', department: 'IT', salary: 60000 },
      { employee_id: 3, employee_name: 'Charlie', department: 'Finance', salary: 55000 },
      { employee_id: 4, employee_name: 'Alice', department: 'IT', salary: 70000 },
      { employee_id: 5, employee_name: 'Bob', department: 'HR', salary: 52000 }
    ];
    
    app.get('/employee/employee-details', (req, res) => {
      const sortBy = req.query.sort_by;
      const validSortFields = ['employee_id', 'employee_name', 'department', 'salary'];
    
      if (!validSortFields.includes(sortBy)) {
        return res.status(400).send({ error: `Invalid sort_by field. Valid fields are: ${validSortFields.join(', ')}` });
      }
    
      const sortedEmployees = [...employees].sort((a, b) => {
        if (a[sortBy] < b[sortBy]) return -1;
        if (a[sortBy] > b[sortBy]) return 1;
        return 0;
      });
    
      res.json(sortedEmployees);
    });
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}/`);
    });
    

    Install dependency and run it

    npm install express
    node mock-server.js
    

    Verify API

    http://localhost:8080/employee/employee-details?sort_by=employee_id

    enter image description here

    http://localhost:8080/employee/employee-details?sort_by=employee_name enter image description here

    http://localhost:8080/employee/employee-details?sort_by=department enter image description here

    http://localhost:8080/employee/employee-details?sort_by=salary enter image description here

    Single Request

    Import this collection

    {
        "info": {
            "_postman_id": "ef4bd661-b94e-4099-b512-a2268c5d5fc5",
            "name": "1-demo",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
            "_exporter_id": "1826150"
        },
        "item": [
            {
                "name": "Get Employee",
                "event": [
                    {
                        "listen": "test",
                        "script": {
                            "exec": [
                                "// Expected values for the first employee ID based on the sort key\r",
                                "const expectedFirstIds = {\r",
                                "    employee_id: 1,\r",
                                "    employee_name: 4,\r",
                                "    department: 3,\r",
                                "    salary: 5\r",
                                "};\r",
                                "\r",
                                "// Get the current sort key from the collection variable\r",
                                "const sortKey = pm.collectionVariables.get(\"sortKey\");\r",
                                "\r",
                                "const responseJson = pm.response.json();\r",
                                "// Check if the first employee ID matches the expected value\r",
                                "pm.test(`The first employee ID for sort key ${sortKey} is correct`, function () {\r",
                                "    pm.expect(responseJson[0].employee_id).to.eql(expectedFirstIds[sortKey]);\r",
                                "});"
                            ],
                            "type": "text/javascript",
                            "packages": {}
                        }
                    },
                    {
                        "listen": "prerequest",
                        "script": {
                            "exec": [
                                "let sortKeys = JSON.parse(pm.collectionVariables.get(\"sortKeys\"));\r",
                                "pm.collectionVariables.set(\"sortKey\", sortKeys.shift())\r",
                                "pm.collectionVariables.set(\"sortKeys\", JSON.stringify(sortKeys));\r",
                                "if (sortKeys.length > 0){\r",
                                "    postman.setNextRequest(\"Get Employee\"); // <- GET Request Name\r",
                                "}"
                            ],
                            "type": "text/javascript",
                            "packages": {}
                        }
                    }
                ],
                "request": {
                    "method": "GET",
                    "header": [],
                    "url": {
                        "raw": "http://localhost:8080/employee/employee-details?sort_by={{sortKey}}",
                        "protocol": "http",
                        "host": [
                            "localhost"
                        ],
                        "port": "8080",
                        "path": [
                            "employee",
                            "employee-details"
                        ],
                        "query": [
                            {
                                "key": "sort_by",
                                "value": "{{sortKey}}"
                            }
                        ]
                    }
                },
                "response": []
            }
        ],
        "event": [
            {
                "listen": "prerequest",
                "script": {
                    "type": "text/javascript",
                    "exec": [
                        ""
                    ]
                }
            },
            {
                "listen": "test",
                "script": {
                    "type": "text/javascript",
                    "exec": [
                        ""
                    ]
                }
            }
        ],
        "variable": [
            {
                "key": "sortKeys",
                "value": "[\"employee_id\", \"employee_name\", \"department\", \"salary\"]",
                "type": "string"
            },
            {
                "key": "sortKey",
                "value": "employee_id",
                "type": "string"
            }
        ]
    }
    

    After Import enter image description here

    Run Collection

    enter image description here

    Result

    Looping call "Get Employee" request by sortKeys from "employee_id" -> "employee_name" ->"department" to "salary"

    enter image description here