Cannot use variables in GET requests

I have a collection runner that uses a json file to read variable values:

I cannot seem to use them when creating GET requests:

URL:

http://localhost:3000/agents/{{gadget_id}}

Pre-request script:

var gadget_id = pm.iterationData.get(“gadget_id”);

The request URL for all get requests in the collection runner is:

http://localhost:3000/agents/

NO VARIABLE VALUE HAS BEEN ASSIGNED. WHY?

Hey @Sebi

Can you provide some screenshots so we can see what’s going on please?

Do any of the request tabs have orange dots on them? If they do, you need to save those so the runner knows about those changes.

Can you provide some screenshots so we can see what’s going on please?

Do any of the request tabs have orange dots on them? If they do, you need to save those so the runner knows about those changes.

Everything’s saved (green).

Edit:

In these screenshots “gadget_id” has been replaced with “agent_id” but the requests are identical this aside.

Could expand the view of the request builder to show the request tabs, do any of these have orange dots on them. Not sure what you mean by ‘green’ the tab shouldn’t show any colour.

Have the created a new run or are you retrying the same one as before?

Ok. It works after reimporting the data file. But there’s still a problem; it creates requests even when the agent_id is empty. Is it possible to set conditions on the requests (drop request is variable value if null/empty)?

E.g:

{
    "url": "http://localhost:3000/users/",
    "gadget_id": "",
    "user_id": "9d788283-87a9-4c38-8d48-30ddc1604058"
},

Don’t make request for gadget_id like

www.url.com/gadgets/{{gadget_id}}

gadget_id is empty so don’t even make the request.

Something like this:

Something that I’ve done to handle this scenario is just to change the url the request is hitting via the prerequest script. Let’s take an example.

Say you don’t want to execute the request when gadget_id is null. You could do something like this in your prerequest script;

const gadgetId = pm.iterationData.get('gadget_id');
if(!gadgetId) {
  pm.request.url = 'https://postman-echo.com/delay/0';
  pm.request.method = 'GET';
  pm.variables.set('skip', true);
}
else {
  // If you need to do any other preprocessing if gadget_id exists
}

This will still execute a request, but instead of hitting your API, it will hit the postman echo api.
Since you don’t want tests to run (because your api didn’t actually run), you’d want to add this to your tests tab:

const skip = pm.variables.get('skip');
if(!skip) {
  // all of your tests for your API
}

Essentially you’re just putting your tests behind an if statement to make sure they aren’t run if you ‘skipped’ the request.

Does this all make sense?

2 Likes

I’ve figured it out (created tests based on the entries in the data file (expect to fail and expect to pass)) based on what’s being read (in this case the gadget_id).

1 Like