Alternating responses to the same mock server endpoint

Archived topic — some details may be out of date.
Mock servers built from saved collection examples are still supported. Postman now also has code-based mocks: JavaScript request handlers plus a config.yaml, stored as files in your Git repository, which you can run locally or deploy. Create one in the app, or use the Postman CLI to generate one from an OpenAPI spec, collection or dataset (postman mock generate) and run it (postman mock run). See About mocks and Create a mock.
Working with an AI coding agent? The Postman plugin can build and run mocks for you.
For current help, see the Postman docs, try the free Postman tools (no account needed), or join us on Discord.

Your question may already have an answer on the community forum. Please search for related topics, and then read through the guidelines before creating a new topic.

Here’s an outline with best practices for making your inquiry.

My question:
Hi, long story short is I’m looking for a way to alternate the return value of a mock server endpoint from one request to the other. My mock server is based on an API my app service is expected to hit; it will repeatedly hit a specific endpoint for data until the return ID eventually returns as a blank string rather than a Guid (see below), providing an exit condition for my loop.

image

I have created an example for the endpoint where a ‘returnUuid’ collection variable is returned, and written a pre-requisite script that will update the value of that variable based on its current value, alternating between a new random guid and an empty string.

Hitting the endpoint repeatedly in Postman shows that this does work; however hitting it from either a browser or from my app shows the value not changing from whatever it happens to currently be set to. I may be making the incorrect assumption that scripts would run in this situation. If so then is there another way to acheive what I’m looking for here?

Hi @benigoat

Assuming my understanding of your description is correct…
“The pre-request script won’t run if you hit the API from a browser or app”.
The pre-request is executed inside Postman before the API call.

Hi @w4dd325

I just need some clarification on when you say ‘inside Postman’; So if I set up a simple mock server endpoint with a PR script logging something to the console, and hit that URL through a browser, I don’t see anything in the console. Is this correct?

Correct, as far as my understanding goes, a browser/app submitting the API call will not trigger the pre-req or test scripts. These live inside Postman and would be triggered when the “Send” button is clicked.