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:

1
const name = 'Nabeel'
2
3
console.log(`Hello ${name}`)

Additionally, postman gives us some functions to set and get environment variables, so we can set the name as an environment variable like so:

1
const name = 'Nabeel'
2
3
pm.environment.set('name', name)

And log it like so:

1
console.log(pm.environment.get('name'))

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:

1
pm.sendRequest('https://randomuser.me/api/', (err, res) => {
2
const apiResponse = res.json()
3
4
// do more stuff
5
})

Using this method, we can get some random user data and set it in the environment variables as follows:

1
pm.sendRequest('https://randomuser.me/api/', (err, res) => {
2
const apiResponse = res.json()
3
4
const user = apiResponse.results[0]
5
6
const email = user.email
7
const firstName = user.name.first
8
const lastName = user.name.last
9
10
pm.environment.set('email', email)
11
pm.environment.set('firstName', firstName)
12
pm.environment.set('lastName', lastName)
13
})

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

1
{
2
"email": "{{email}}",
3
"firstName": "{{firstName}}",
4
"lastName": "{{lastName}}"
5
}

Postman will then populate the slots from the environment variables that we set automatically when making the request