Use path variable as variable in mock server response

I’m building mocked APIs using examples.
The faker library to create random bits and pieces (https://learning.postman.com/docs/writing-scripts/script-references/variables-list/) is awesome to mock the creation of a new resource.

However a common pattern we have does not work with this.
We have a Restful API, so usually we have something along the lines: https://api.com/resource/:id

With Postman I can now nicely return a static JSON response and with that faker library I can even generate random data so that it is always looking different.
However what I would need to do is to have that :id from the path inside the JSON.

So that a request to https://api.com/resource/3 returns
{“id”: 3, …}
and one to to https://api.com/resource/341894 returns
{“id”: 341894, …}

So essentially a way to have the path variable as a variable for the response.

How can I achieve this? This would enable us to build mock APIs with ease!
Thank you

Hi @lukaswelte,

Welcome to the community! :clap:

This is a great question, and something that would make mocking even better. Fortunately, you should be able to do this, and I verified with my current testing.

The way you can go about this is to generate a fake ID with your faker library, and persist that as an environment variable using your pre-request script. Then, in your mocked example, include that variable for the id value, like so:

{ "id": {{fakerId}}, ... }

This should give you the functionality you are looking for.

Orest

Thank you for the response.
I’m glad that this is possible, but it seems quite hacky with having to pass this through a pre request script in order to use the request path variable in the response (would be really handy if those automatically get part of the response variables).

But I understand that this is what currently is available.
Thank you :slight_smile:

Certainly!

If you are interested in seeing this as a feature for Postman, you can create a feature request on github and the engineering team can review it that way.

Nonetheless, glad there is some way you can get this functionality you desire. Glad I can help :slight_smile: