How to randomize response data from a mock server?

I would like to create a mock server that replies semi-dynamically to a POST request. There would be two variations of the 200-OK, replying either with ‘false’ or ‘true’ and a set of JSON-data.

I was hoping the mock server could randomly switch between these examples. The reply for either scenario may be hardcoded, as long as it switches between the examples.

I would settle for using variables on Collection level uses the RandomInt(0,1) script and depending on the outcome, include either the content of variable ‘reply-0’ or ‘reply-1’. If we’d go this way, I was hoping someone could give me a head start with some code :grin:

I could use a variable in my application that could switch between two mock requests, to simulate different responses. However, this doesn’t feel the way mock servers should be used and will result in a lot more changes once the actual API is built.

Hi @sjeefr,

You can use a dynamic variable to randomly generate a boolean. Just add it to the response body of your example, like so:

{
  "hasSuperPowers": {{$randomBoolean}},
  "name": "The Tick"
}

Hope this helps!

Best,

Kevin

Hey Kevin,

thanks for your reply! That helps halfway! It would be nice to hide ‘name’ when hasSuperPowers is false in the response. Is that possible?

p.s. The Tick is still on my watchlist. You enjoyed it?

Hey @sjeefr,

I don’t know of a way to programmatically alter the example being returned at runtime other than with dynamic variables. Are the request bodies different for each response body model? If so, you can make 2 examples, include those request bodies in each example, shape the responses differently, and set the x-mock-match-request-body header to true. Refer to the matching algorithm for mocks for more info.

PS: I only saw a few episodes of The Tick on Amazon Prime Video. But the 90s cartoon was pretty rad!

1 Like

Hello @kevin.swiber,

I was already using your suggestion, but did not know about the header. When setting this to true, the mock server switches between examples, but only if the request body matches the example request body.

The input would be a person name and a postal code. I was hoping that the algorithm used for selecting an example would use a ‘best match’, instead of an ‘exact match’ search. There are thousands of postalcode variations and I cannot create that many examples, obviously :slight_smile:

Unless you know a way to have it select a best match, instead of exact match, I think that Postman lacks the features I need.

Thanks.