Published on

Generating data before sending a request

image
Authors
  • avatar
    Name
    David Jimenez
    Twitter

In a previous post we learned how to use environment varibles to share data between requests. In that example, we requested a token, and stored it in an environment variable so that we could be reuse it to authenticate future requests.

In that scenario the data that we were sharing was captured after the request was made. However, there may be scenarios where we want to generate data before sending a request.

Going back to our test collection, assume that we want to test that creating accounts works. We don't necessarily care what values we use. A simple solution would be to leverage Postman utilities to generate random data:

Random Data

{{$randomFullName}}, {{$randomEmail}}, and {{$isoTimestamp}} are generated by Postman. An easy way to tell is that the variable names all start with a dollar sign.

What if we wanted to save those variables to our environment? The first step is to add the variables to the environment. For this example, we'll add three: random_name, random_email, and today_date,

New Variables

Then in the request's Pre-request Script tab we add JavaScript to populate these variables before making the request:

Pre-request script

Two things to note:

  • We can still leverage Postman utilities to generate random data. This generates a random email address
pm.variables.replaceIn('{{$randomEmail}}')`
  • We can use the moment plugin to generate today's date using a year-month-day format.