How To Use Regular Expression In Postman
Harnessing the Power of Regular Expressions in Postman for Robust API Testing
Regular expressions (regex) are a powerful tool for pattern matching in text, and they can significantly enhance your API testing efforts in Postman. Here’s how to effectively leverage regex in Postman for more comprehensive and efficient testing.
1. Understanding Regular Expressions
Before diving into Postman, let’s quickly grasp the fundamentals of regex. Regular expressions are sequences of characters that define a search pattern. They use special characters (metacharacters) to represent a range of possibilities, allowing flexible and precise matching.
Example: The regex \d+
matches one or more digits. In a response body like “The order ID is 12345,” this pattern will match the “12345” part.
2. Using Regular Expressions in Postman Tests
Postman’s test scripts allow you to integrate regex for validation and assertion purposes.
Step 1: Accessing the Test Tab
After sending your API request, navigate to the “Tests” tab within the Postman interface.
Step 2: Writing a Test Script
In the “Tests” tab, you can write JavaScript code to validate the response data.
Step 3: Incorporating Regular Expressions
Postman utilizes the pm.test()
function for writing test assertions. Within this function, you can use the pm.expect(actualValue).to.match(regexPattern)
method to check if the actualValue
matches the specified regexPattern
.
Example:
pm.test("Response body contains a valid email address", function () { let responseBody = pm.response.text(); pm.expect(responseBody).to.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/);});
This test checks whether the response body contains a valid email address using a regex pattern specific for email validation.
3. Common Regex Patterns for API Testing
Here are some commonly used regex patterns in API testing:
1. Validating Numbers:
\d+
: Matches one or more digits.\d{3}
: Matches exactly 3 digits.[0-9]{1,3}
: Matches 1 to 3 digits.
2. Validating Strings:
^[a-zA-Z]+$
: Matches a string containing only letters.^[a-zA-Z0-9]+$
: Matches a string containing only letters and numbers.[a-z]{5,10}
: Match a string with 5 to 10 lowercase letters.
3. Validating Date Formats:
\d{4}-\d{2}-\d{2}
: Matches a date in the formatYYYY-MM-DD
.\d{1,2}/\d{1,2}/\d{4}
: Matches a date in the formatMM/DD/YYYY
.
4. Validating API Endpoints:
/api/users/[0-9]+
: Matches an endpoint like/api/users/123
./api/products/[a-zA-Z0-9-]+
: Matches an endpoint like/api/products/product-123
.
4. Using Regex in Postman Variables
Postman’s variables provide a mechanism to store and reuse data throughout your tests. You can use regex to extract specific information from the response and store it in variables.
Step 1: Defining a Variable
Use the pm.variables.set()
function to define a new variable.
Step 2: Extracting Data with Regex
Use the pm.response.text().match(regexPattern)
function to extract data that matches the regexPattern
.
Step 3: Assigning the Extracted Data
Assign the extracted value to the variable using pm.variables.set(variableName, extractedData)
Example:
pm.test("Extract order ID from response", function () { let responseBody = pm.response.text(); let orderID = responseBody.match(/"order_id":\s*(\d+)/)[1]; // Extracts the order ID pm.variables.set("orderId", orderID); // Stores the extracted value});
5. Using Regex in Postman Assertions
You can integrate regex directly into Postman’s assertions for more refined validation.
Example:
pm.test("Response body contains the order ID 12345", function () { let responseBody = pm.response.text(); pm.expect(responseBody).to.include("order_id\": 12345"); // Includes a fixed value});
pm.test("Response body contains any order ID", function () { let responseBody = pm.response.text(); pm.expect(responseBody).to.match(/"order_id":\s*(\d+)/); // Includes a regex pattern});
6. Advanced Regex Techniques in Postman
1. Grouping and Capturing:
Use parentheses ()
in your regex to create groups. You can then access the captured groups using the match()
method.
2. Lookarounds:
Use lookarounds like (?=...)
and (?<...)
to match specific patterns without including them in the final match.
3. Backreferences:
Use \1
, \2
, etc., to refer to previously captured groups within the same regex pattern.
4. Using the exec()
Method:
The exec()
method provides more detailed information about your regex matches, including matched groups.
7. Online Regex Testing Tools
Use online regex testing tools like Regex101 or RegExr to experiment with different regex patterns. These tools allow you to test your regex on various sample strings and provide insights into the different matches and groups.
By incorporating regex into your Postman test scripts, you can create more robust and comprehensive API tests that can handle a wider range of responses and ensure the quality of your API endpoints.