Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 30 ยท Organizing Work

Dynamic variables and generated test data

Learn every family of Postman dynamic variables, how to use them in bodies and scripts, how to keep a generated value for later requests, and how to make test data repeatable.

Tests that always send the same data fail in annoying ways. A "create user" request works once and then returns 409 Conflict because the email already exists. A search test passes only because the database happens to contain one famous record. To avoid this you need fresh, realistic data on every run, and Postman gives it to you with dynamic variables.

A dynamic variable is a built-in name that starts with a dollar sign, such as {{$guid}} or {{$randomEmail}}. Each time Postman sends a request it replaces the name with a newly generated value. You do not define them anywhere; they are always available. This lesson lists the families, shows the three places you can use them, and fixes the biggest trap: a dynamic variable gives a different value every time it is written, so you must store a value if you need to use it twice.

Postman itself cannot run here. The examples use a small JavaScript stand-in for the generator so you can see how substitution and storing behave. The variable names are the real ones.

The families of dynamic variables

Postman groups its generators by theme. You rarely need more than a few, but it helps to know the shape of the list so you can guess a name.

Family Examples Typical use
Identifiers and time $guid, $randomUUID, $timestamp, $isoTimestamp, $randomAlphaNumeric Unique keys, idempotency keys, correlation ids
Numbers and flags $randomInt (0 to 1000), $randomBoolean, $randomPrice, $randomColor, $randomHexColor Quantities, prices, toggles
People $randomFirstName, $randomLastName, $randomFullName, $randomNamePrefix, $randomJobTitle User profiles
Contact and internet $randomEmail, $randomExampleEmail, $randomUserName, $randomPassword, $randomPhoneNumber, $randomUrl, $randomDomainName, $randomIP, $randomIPV6, $randomMACAddress, $randomUserAgent, $randomProtocol, $randomSemver Registration forms, network fields
Places $randomCity, $randomStreetAddress, $randomCountry, $randomCountryCode, $randomLatitude, $randomLongitude Addresses, geo data
Dates $randomDateFuture, $randomDatePast, $randomDateRecent, $randomWeekday, $randomMonth Bookings, expiry dates
Money and finance $randomCurrencyCode, $randomBankAccount, $randomBankAccountIban, $randomCreditCardMask, $randomTransactionType, $randomBitcoin Payment-like payloads
Business $randomCompanyName, $randomCompanySuffix, $randomCatchPhrase, $randomBs Organizations
Commerce $randomProduct, $randomProductName, $randomProductAdjective, $randomProductMaterial, $randomDepartment Catalog items
Words and text $randomWord, $randomWords, $randomPhrase, $randomNoun, $randomVerb, $randomAdjective, $randomLoremWord, $randomLoremSentence, $randomLoremParagraph, $randomLoremText, $randomLoremSlug Titles, descriptions, comments
Files $randomFileName, $randomFileExt, $randomFilePath, $randomDirectoryPath, $randomMimeType, $randomCommonFileName Upload tests
Images $randomImageUrl, $randomAvatarImage, $randomAbstractImage, $randomCatImage Avatars, galleries
Databases $randomDatabaseColumn, $randomDatabaseType, $randomDatabaseEngine Schema-like fields

The exact set can change between Postman versions, so when a name is not recognized, type {{$ in any field and use the autocomplete list.

Two details are worth remembering. $randomEmail produces addresses on real-looking domains; use $randomExampleEmail when you must stay on example.com-style domains so no real mailbox is ever contacted. And $randomPassword generates a string that is long and mixed, but it is not guaranteed to satisfy your own password policy, so validate that before relying on it.

Where you can use them

In the request builder. Put a name in the URL, a header, a form field or the body. The substitution happens on send:

JSON
{
  "id": "{{$guid}}",
  "name": "{{$randomFullName}}",
  "email": "{{$randomExampleEmail}}",
  "age": {{$randomInt}},
  "createdAt": "{{$isoTimestamp}}"
}

Notice that {{$randomInt}} has no quotes, because a number should be a JSON number. That template is not valid JSON until Postman fills it in, which is fine, since Postman substitutes before sending.

In a pre-request script. Scripts cannot write {{$guid}} and have it expanded automatically. Use pm.variables.replaceIn, which expands a string the way the request builder would:

JavaScript
const email = pm.variables.replaceIn("{{$randomExampleEmail}}");
pm.collectionVariables.set("newEmail", email);

In the Postman sandbox you also have access to the postman-collection helpers and a few libraries, but replaceIn is the simplest bridge to the dynamic variables.

In the Collection Runner and Newman. Dynamic variables work in runs too, so a regression suite creates fresh data each iteration. This is also why such runs can be hard to reproduce, which we fix at the end.

The trap: every use is a new value

Suppose a request body contains {{$randomEmail}} and a test later checks that the response echoes the email you sent. Postman cannot know which value it generated, because writing the variable twice yields two different results. The same goes for using {{$guid}} in the URL and again in the body: they will not match.

The solution is to generate once, store the result in a normal variable and then use that variable everywhere:

JavaScript
// Pre-request script
const email = pm.variables.replaceIn("{{$randomExampleEmail}}");
pm.variables.set("email", email);        // local scope: exists for this request only

Now the body uses "email": "{{email}}", and the Tests tab can compare against pm.variables.get("email"):

JavaScript
// Tests tab
pm.test("response echoes the email we sent", () => {
  pm.expect(pm.response.json().email).to.eql(pm.variables.get("email"));
});

Choose the scope on purpose. A local variable disappears after the request; use an environment or collection variable when later requests, such as "get the user we just created", need the value. See Environments and variables for scope rules and Chaining requests and workflows for passing values along.

Seeing the behavior

The stand-in below mimics replaceIn. It has a handful of generators and expands every {{$name}} it finds. Run it and compare the two lines: the same template, written twice, gives two different values, while a stored value stays fixed.

JS A tiny dynamic-variable expander

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Realistic data that stays valid

Random data must still pass your API's validation, and random values can collide with business rules. A few practical patterns:

  • Unique but recognizable. Prefix generated values so you can find and clean them up: "name": "autotest-{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}". A nightly cleanup job can then delete everything starting with autotest-.
  • Bounded numbers. $randomInt returns 0 to 1000. For an age or a quantity, compute your own range in a script: 1 + Math.floor(Math.random() * 5).
  • Valid enums. A random word is rarely a valid status. Pick from a list instead: ["new","paid","shipped"][Math.floor(Math.random() * 3)].
  • Dates in order. Two independent random dates may put the end before the start. Generate one and derive the other.
  • Do not leak real people. Generated names and emails are fictional, but if you point $randomEmail at a staging system that sends real mail, you might hit a real address. Prefer the example-domain variants.
JS Constrained random data with a recorded seed

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Making failures reproducible

Because dynamic variables are random, a run that failed last night cannot be replayed exactly. Three habits help:

  1. Log what you generated. Call console.log in the pre-request script for the stored values; the Postman Console and the Newman output then show the data that triggered the failure.
  2. Put the values into test names or messages for important checks: pm.test("created " + email, ...).
  3. Use data files when you need exact repeatability. A CSV or JSON data file in the Collection Runner gives identical inputs every run (see The Collection Runner and data-driven testing). A good suite mixes both: fixed data for known edge cases, generated data for "this should work for anyone".

Postman's built-in generators cannot be seeded. If you need a seeded generator, write a few lines of JavaScript as in the stand-in above, or keep the seed in a variable and feed it through your script.

Common mistakes

  • Using the variable twice and expecting equal values (store it first).
  • Forgetting quotes rules: strings need quotes in JSON, numbers and booleans do not.
  • Using {{$randomEmail}} against a system that really sends email.
  • Assuming a random value always satisfies validation, such as password rules or enum values.
  • Leaving generated data behind. Pair creation requests with a cleanup step at the end of the run.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You write {{$guid}} in the URL and again in the JSON body. What do you get?

    Every occurrence of a dynamic variable is expanded on its own. Generate once and store the value in a normal variable to reuse it.
  2. 2. How do you expand a dynamic variable inside a pre-request script?

    replaceIn expands variable references in a string, including dynamic ones, and returns the result.
  3. 3. Which choice is safest when a staging system sends real emails?

    The example-email variant stays on reserved example domains, so no real mailbox is contacted.
  4. 4. What best makes a randomly generated failure reproducible later?

    Postman's built-in generators are not seeded, so record what was generated or use fixed data for cases that must repeat.

Summary

  • Dynamic variables ({{$guid}}, {{$randomInt}}, {{$randomFullName}} and many more) produce fresh values on every send.
  • They are grouped into families: identifiers, numbers, people, internet, places, dates, finance, commerce, text, files and images.
  • Use them in the request builder, or expand them in scripts with pm.variables.replaceIn.
  • Each occurrence is a new value, so generate once and store the result when you need to compare or reuse it.
  • Constrain random data so it passes validation, tag it for cleanup and log it so failures can be replayed.

Next: Pre-request scripts.