Skip to content

How To Use Regex In Postman

API Testing Blog

Mastering Regular Expressions in Postman for Robust API Testing

Regular expressions (regex) are powerful tools for pattern matching in strings. In API testing, they enable you to:

  • Validate data formats: Ensure responses adhere to predefined structures.
  • Extract specific information: Retrieve desired values from complex JSON payloads.
  • Dynamically generate test data: Create realistic inputs for testing various scenarios.

Let’s dive into practical examples showcasing how to leverage regex within Postman.

1. Validating Data Structures with Regex in Postman

Imagine you’re testing an API that returns a user’s email address. You want to confirm it follows the standard email format. Regex can be your data validation superhero.

Step 1: Define the Regex Pattern

The following regex pattern matches a typical email format:

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

This pattern specifies:

  • ^: Start of the string.
  • [a-zA-Z0-9._%+-]+: One or more alphanumeric characters, periods, underscores, percent signs, plus or minus signs, and at signs.
  • @: Literal at sign.
  • [a-zA-Z0-9.-]+: One or more alphanumeric characters, periods, and hyphens.
  • \.: Literal period.
  • [a-zA-Z]{2,}$: Two or more alphabetic characters at the end of the string.

Step 2: Integrate Regex into a Postman Test

pm.test("Email format validation", () => {
const email = pm.response.json().email;
pm.expect(email).to.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/);
});

This test retrieves the “email” field from the response, uses pm.expect(email).to.match(), and applies the regex pattern to verify its validity.

2. Extracting Data from API Responses with Regex

Sometimes you need to extract specific information, like a user ID, from a complex response. Regex can help you precisely target and retrieve the data you need.

Example Scenario: Extracting User ID from a JSON response

Let’s assume the API returns the following JSON:

{
"user": {
"id": "12345",
"name": "John Doe",
"email": "john.doe@example.com"
}
}

Step 1: Identify the Target Data

You want to extract the “id” value, which is enclosed in quotation marks.

Step 2: Define the Regex Pattern

The following pattern captures the user ID:

"id": "([^"]+)"

Breakdown:

  • "id": ": Matches the literal string “id”: “.
  • ([^"]+): Capturing group that matches one or more characters that are not quotation marks.

Step 3: Extract the Value using Postman’s pm.test()

pm.test("Extract User ID", () => {
const userId = pm.response.text().match(/"id": "([^"]+)"/)[1];
pm.expect(userId).to.equal("12345");
});

This test extracts the captured group (the user ID) using the match() function and verifies its value.

3. Generating Dynamic Test Data with Regex

Regex can also help you create realistic test data for your API requests.

Example Scenario: Generating Random Email Addresses

Instead of hardcoding email addresses, you can use regex to generate different ones for your test runs.

Step 1: Define the Regex Pattern

The following pattern generates email addresses with varying lengths, domains, and top-level domains:

[a-z]{5,10}[.a-z0-9]+@[a-z]{5,10}[.]{1}[a-z]{2,4}

Breakdown:

  • [a-z]{5,10}: Matches 5 to 10 lowercase letters (username).
  • [.a-z0-9]+: Matches one or more periods, lowercase letters, and digits (optional part of the username).
  • @[a-z]{5,10}: Matches 5 to 10 lowercase letters (domain).
  • [.]{1}: Matches one period.
  • [a-z]{2,4}: Matches 2 to 4 lowercase letters (top-level domain).

Step 2: Integrate Regex into Postman’s pm.variables

pm.variables.set("randomEmail", /[a-z]{5,10}[.a-z0-9]+@[a-z]{5,10}[.]{1}[a-z]{2,4}/.exec()[0]);

This code snippet uses pm.variables.set() to store a randomly generated email address based on the regex pattern.

Step 3: Utilize the Dynamic Variable in Your Request

In the request body or URL parameters, use {{randomEmail}} to dynamically substitute the generated email address.

4. Simplifying Assertion Logic with Regex

Instead of writing complex assertions with nested conditions, regex can simplify your validation logic.

Example Scenario: Validating a Phone Number

Suppose you need to check if the user’s phone number is in a specific format, like (XXX) XXX-XXXX.

Step 1: Define the Regex Pattern

^\(\d{3}\) \d{3}-\d{4}$

This pattern matches:

  • ^: Start of the string.
  • \(: Literal opening parenthesis.
  • \d{3}: Three digits.
  • \): Literal closing parenthesis.
  • : Space character.
  • \d{3}: Three digits.
  • -: Literal hyphen.
  • \d{4}: Four digits.
  • $: End of the string.

Step 2: Use Regex in Postman’s Test

pm.test("Phone Number Format Validation", () => {
const phoneNumber = pm.response.json().phone;
pm.expect(phoneNumber).to.match(/^\(\d{3}\) \d{3}-\d{4}$/);
});

This simple test, using regex, verifies the phone number format without requiring complex conditional statements.

5. Beyond Basic Regex: Working with Complex Patterns

As you become more familiar with regex, you’ll encounter complex scenarios requiring advanced techniques.

Example: Matching Multiple Options

Imagine you need to validate a status code, which can be either “success” or “pending”.

Step 1: Utilize the Or Operator (|)

The regex pattern:

^(success|pending)$

Matches either “success” or “pending” at the beginning and end of the string.

Step 2: Apply the Regex in Test

pm.test("Valid Status Code", () => {
const status = pm.response.json().status;
pm.expect(status).to.match(/^(success|pending)$/);
});

This test verifies the status field matches either “success” or “pending” using regex.

Final Thoughts

Regular expressions empower you to write more robust and efficient API tests. They help you validate data formats, extract information, generate dynamic data, and simplify assertions, ultimately contributing to a comprehensive and reliable testing process. Embrace regex in Postman, and unleash the power of pattern matching for your API testing endeavors.

API Testing Blog