Schedule runs - getting a variable to increment

I am trying to hit one of my endpoints from a scheduled run.
I need the id field to update after each run:
envVariableCommunity

There is plenty of help out there - and I have been successfully running this manually.
My variable updates after each post.

However as soon as it runs under schedule it does not update.

I have tried using collection variables and environment variables.

I have even tried the very hidden setting in Postman: “Autosave”
(but this makes no difference)

I am told that cloud only accesses the ‘initial’ variable values whereas local access the ‘latest’ value. But how do I get ‘initial’ values to update programatically after each run?

Anyone know what I’m doing wrong?
I can’t believe it is so difficult to schedule cloud-based operation with an incrementing counter.

Finally, here is a screenshot of the schedule tests.
THe varaibles are stuck on 7 (pre) and 8 (post) when I run from cloud.

Any help would be greatly appreciated.

I think I understand what you are saying now.

When you run the collection from a monitor or scheduled job, the variables only persist for that run.

Therefore, the next time the scheduled job runs, it will start with the initial values each time.

This is different (but similar) to the local variables only persisting for the current request.

I don’t know if its possible to save data between runs. Hopefully someone with more experience of running scheduled jobs will be able to answer that.

to clarify.
My schedule hits the endpoint every 15 minutes.

I want it to increment the counter each time it runs (every 15 mins)
5,6,7,8,9 etc…

I also want it to start at a number other than zero - which seems equally elusive.

@doug

I understand what you are trying to achieve but I don’t know if monitor or scheduled jobs allow you to persist data between runs as I don’t use these features (so have little experience apart from setting up a simple one during the learning centre training).

Hopefully someone from Postman or another user who has more experience with these features will be able to provide a solution.

1 Like

The following topic is similar.

How to update variables while running a collection in a monitor - :person_raising_hand: Help - Postman Community

It involves using an environment, and then calling the Postman API to update the environment.

It is a few years old, so there might be an easier way to achieve this now.

1 Like

Hey @doug :wave: ,

You should be able to use something like this, as part of your Tests script to update the environment variable using the Postman API:

const options = {
    url: 'https://api.getpostman.com/environments/<Environment_ID>',
    method: 'PUT',
    header: {
        'X-API-Key': '<Postman_API_Key>'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            'environment': {
                'name': '<Environment Name>',
                'values': [
                    {
                        'key': '<key_name>',
                        'value': '<value>'
                    }
                ]
            }
        })
    }
}

pm.sendRequest(options, (error, response) => {
    if (error) {
        console.log(error)
    }
    console.log(response.json())
})
1 Like

Hi Danny,

many thanks for getting back to me!

So, can I just check. In the ‘scheduled run’ editor I’m able to set an environment.
Which has variables that I am able to read and write to when I run manually.

However, you’re saying that when scheduling I actually have to make a separate API call to the Postman cloud to update my variables?

Even though this configuration page gives the impression that I’m already connected to that environment?
Even though this is written nowhere on that page - and that page is for editing scheduled runs.

Hi again Danny,

another question. So I amended as you recommended and it overwrote my entire environment - all the variables are now gone. Apart from the one I was trying to update.

Is this expected behaviour?

Hey @doug

That’s my bad :pray: - That PUT call replaces the whole environment :cry:

You’ll need to either call the GET /environment/uuid endpoint to retrieve all the values and append the new one you want to capture to the payload and then send through the PUT call again.

We currently don’t expose that single update operation in the Postman API but I’m speaking with the team now to create a ticket to get that exposed, as it’s a useful operation when doing actions like this.

:frowning:

okay thanks Danny. Really hoping they can recover this environment for me.
(have an open ticket with Postman support for that :pray:)
I was not expecting this!

Can I rewind and ask the same question to you (that I have been asking support)?

I am trying to use a scheduled run to hit one of my APIs every 15 mins.
I need a variable to increment a counter each time.

Is it really so hard?? It seems super-simple to me and yet I’ve been on an 8 day wild-goose chase with Postman support and community and still don’t seem anywhere near a solution. In fact I’m now going backwards.

  • environment overwritten
  • my variable must be written as a string but I need it to be a number.

Thanks for any (other) suggestions. :crazy_face:

Cheers
Doug

Let’s try and get you unblocked and going again. :pray:

It’s slightly too late now but Collections and Environments can be forked, if you ever wanted to have a ‘main’ copy, just incase incidents like this occur. Hopefully, that can be recovered for you.

On the string/number variable type, everything that’s stored as a variable is a string. If you want to use that value as a number, you would need to convert that using parseInt(variable_value) in the scripts before using it.

Let me try some different things out for the getting/updating the environment variables and get back to you tomorrow. I just need to get the flow right before sharing something.

1 Like

Thanks Danny,

looking forward to seeing what you come back with.

I actually have the exact same issue.
I want to schedule a collection run and in there access a variable that was generated by another scheduled run. Intuitively, I used a Global variable. I since learned that isn’t working. I tried an Environment variable and learned that only the “initial value” can be accessed, not the “current value” (wondering why… :thinking:).
And even Collection variables created in the same scheduled collection run can’t be accessed.

I’m losing my mind here :exploding_head: How is anybody getting any work done with scheduled collection runs without accessing outside variables?

Thankful for any hints here.

Hi Florian,

yes, this was such a frustrating experience.

The entire Postman UI and help seem to indicate that it is both possible and easy using the mechanisms already in place. It seems to suggest you can use existing constructs such as environment variables, which is even displayed on the monitor setup screen. But after nearly 2 weeks of trying and failing and asking support (which was also terrible) I had to give up.

Luckily for me my idea of using a ‘self-incrementing’ real world thing (ie a timestamp) worked instead for my purposes.

In the end, to be fair to Postman, I did get an apology about the sub-optimal support and a full script (see below coz this forum doesn’t let you attach JSON) showing how to actually do this (I never actually tried it).

But Postman really need to sort out the disconnect between their UI and what is actually achievable using Cloud variables.

Here is the JSON example I was given…

{
	"info": {
		"_postman_id": "2729a578-b6c0-4983-b719-382e120f5382",
		"name": "Persist-value-collection",
		"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
		"_exporter_id": "16238262"
	},
	"item": [
		{
			"name": "Random Post Data",
			"event": [
				{
					"listen": "prerequest",
					"script": {
						"exec": [
							"let currentCount = pm.environment.get(\"count\");",
							"    currentCount = parseInt(currentCount); ",
							"",
							"//We get the value of the count and parse it to int (Postman stores variable data as strings)",
							"pm.environment.set(\"count\", currentCount + 1);",
							""
						],
						"type": "text/javascript"
					}
				},
				{
					"listen": "test",
					"script": {
						"exec": [
							""
						],
						"type": "text/javascript"
					}
				}
			],
			"request": {
				"method": "POST",
				"header": [],
				"body": {
					"mode": "raw",
					"raw": "{\n    \"message\": \"Sending message number: {{count}}\"\n}",
					"options": {
						"raw": {
							"language": "json"
						}
					}
				},
				"url": {
					"raw": "postman-echo.com/post",
					"host": [
						"postman-echo",
						"com"
					],
					"path": [
						"post"
					]
				}
			},
			"response": []
		},
		{
			"name": "Update Environment",
			"event": [
				{
					"listen": "prerequest",
					"script": {
						"exec": [
							""
						],
						"type": "text/javascript"
					}
				},
				{
					"listen": "test",
					"script": {
						"exec": [
							"console.log(`Updated the count. Current count is ${pm.environment.get('count')}` );"
						],
						"type": "text/javascript"
					}
				}
			],
			"request": {
				"auth": {
					"type": "apikey",
					"apikey": [
						{
							"key": "key",
							"value": "X-API-Key",
							"type": "string"
						},
						{
							"key": "value",
							"value": "{{api_key}}",
							"type": "string"
						}
					]
				},
				"method": "PUT",
				"header": [],
				"body": {
					"mode": "raw",
					"raw": "{\n    // The environment will be updated with the below key/value pairs, anything else will be deleted\n    \"environment\": {\n        \"name\": \"{{env_name}}\",  \n        \"values\": [\n            {\n                \"key\": \"count\",\n                \"value\": \"{{count}}\"\n \n            },\n            {\n                \"key\": \"api_key\",\n                \"value\": \"{{api_key}}\"\n \n            }\n   \n        ]\n    }\n}",
					"options": {
						"raw": {
							"language": "json"
						}
					}
				},
				"url": {
					"raw": "https://api.getpostman.com/environments/{{env_id}}",
					"protocol": "https",
					"host": [
						"api",
						"getpostman",
						"com"
					],
					"path": [
						"environments",
						"{{env_id}}"
					]
				}
			},
			"response": []
		}
	],
	"event": [
		{
			"listen": "prerequest",
			"script": {
				"type": "text/javascript",
				"exec": [
					""
				]
			}
		},
		{
			"listen": "test",
			"script": {
				"type": "text/javascript",
				"exec": [
					""
				]
			}
		}
	],
	"variable": [
		{
			"key": "env_id",
			"value": "16238262-2273310a-8844-46c4-ae49-cd512792bf92",
			"type": "string"
		},
		{
			"key": "env_name",
			"value": "Test Env",
			"type": "string"
		}
	]
}