Generate data for a Postman request
24 November 2020
Updated: 03 September 2023
When making requests with Postman to test an API it is often useful to have generated data, for example when creating users in a backend system you may want the ability to get custom user data
The method we will use to do this is by setting Postman environment variables in the Pre-request Script of a Postman request
Firstly, we can write some basic logging in the Pre-request script section on Postman and view the result in the Postman console:
Additionally, postman gives us some functions to set and get environment variables, so we can set the name as an environment variable like so:
And log it like so:
Aditionally, we can make HTTP Requests using pm.sendRequest
which then takes a callback for what we want to do after the request, we can use the randomuser
api to get a user:
Using this method, we can get some random user data and set it in the environment variables as follows:
We can then use this in our request body using Postman’s {\{}\}
syntax. If we were making a JSON request, our body would look something like this:
POST: https://my-api.com/users
Postman will then populate the slots from the environment variables that we set automatically when making the request