Have dynamic request values matching mock request

Hello there,

So here’s my problem. I have a collection with requests and possible responses that the mock server returns. However in those requests a value could be dynamic like a current date time.

There’s this one request where the user enters a user name and password. And for the test I want to be able to input a valid username for which there’s an exactly matching request which will return a successfull response (200). And I also want to be able to input any other username and password which should result in a 405 for user not found (as that’s what the real server returns).

However the request matching is very rigid which means it has to match exactly. But that’s not the reality. I’ve read numerous topics here and elsewhere with many people requesting exactly what I want, but no useful response is ever given. So here I am attempting to finally get a proper response. This is NOT about dynamic responses. This is about dynamic requests.

Here’s my collection:

Here you can see the login request with its two possible responses.

The request:

The first possible match that returns a successfull response:

The second possible match that returns a failed response:

Currently it’ll only return that error response if the input username and password match with the second request. And what I want is for those values to be dynamic by for instance using a regex.

It has to match the first response so we have a successfull response, but entering any other details should result in the 405 and not in the 404 match not found from postman.

Hey @Teysz :waving_hand:

Welcome to the Postman Community! :postman:

This is more of a workaround than a solution, you could create a pre-request script that checks the request body data that’s been entered and apply a specific header to the request which determines the response.

Here I’m using the x-mock-response-code header but there are other available to point to an example by name or id.

const requestBody = pm.request.body.raw;
const name = JSON.parse(requestBody).login;

if (name !== "admin") {
    pm.request.headers.add({
        key: 'x-mock-response-code',
        value: 405
    });
};

As I mentioned this is only a workaround and you’re adding extra details to your requests that would need to be stripped out once you’re finished with the Mock Server and you start using your own servers.

Thank you! That solves the issue.

1 Like