Using Regular Expressions for API Automation Testing: 10 Practical Examples
This article demonstrates how regular expressions can be applied in API automation testing through ten practical Python examples that extract URLs, validate emails, parse JSON, match phone numbers, detect sensitive words, retrieve HTTP status codes, verify dates, parse query parameters, enforce password strength, and extract XML tag content.
Regular expressions (regex) are extremely useful in API automation testing for extracting specific information from responses and validating that returned content matches expected formats.
Example 1: Extract URLs from HTML
import re
html = 'Example Visit Test Site'
pattern = re.compile(r'href="(http[s]?://(?:[a-zA-Z0-9$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)'")
matches = pattern.findall(html)
print(matches) # ['https://www.example.com', 'http://test.example.org']Example 2: Validate Email Format
email = "[email protected]"
pattern = re.compile(r'^[\w\.-]+@[\w\.-]+\.\w+$')
if pattern.match(email):
print("Valid email")
else:
print("Invalid email") # Valid emailExample 3: Extract Specific Field from JSON Response
json_text = '{"name": "John Doe", "age": 30, "city": "New York"}'
pattern = re.compile(r'"age": (\d+)')
match = pattern.search(json_text)
if match:
age = match.group(1)
print(f"Age: {age}") # Age: 30
else:
print("Age not found")Example 4: Match Phone Numbers
text = "Contact us at +1 (123) 456-7890 or +44-20-7123-4567."
pattern = re.compile(r'\+?\d{1,3}[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}')
phone_numbers = pattern.findall(text)
print(phone_numbers) # ['+1 (123) 456-7890', '+44-20-7123-4567']Example 5: Detect Sensitive Words in a Message
message = "Your order has been processed successfully."
sensitive_words = ["error", "failed"]
pattern = re.compile("|".join(map(re.escape, sensitive_words)))
if pattern.search(message):
print("Message contains sensitive words.")
else:
print("Message is clean.") # Message is clean.Example 6: Extract HTTP Status Code from Log
log_entry = "GET /api/data HTTP/1.1 200 OK"
pattern = re.compile(r'\b\d{3}\b')
status_code = pattern.search(log_entry)
if status_code:
print(f"Status Code: {status_code.group()}") # Status Code: 200
else:
print("No status code found.")Example 7: Validate Date Format (YYYY-MM-DD)
date_str = "2023-04-01"
pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')
if pattern.match(date_str):
print("Valid date format")
else:
print("Invalid date format") # Valid date formatExample 8: Extract Query Parameter from URL
url = "https://www.example.com/search?q=python+regex⟨=en"
pattern = re.compile(r'q=(.*?)(&|$)')
match = pattern.search(url)
if match:
query = match.group(1)
print(f"Search Query: {query}") # Search Query: python+regex
else:
print("Query parameter not found")Example 9: Check Password Strength
password = "P@ssw0rd"
pattern = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$')
if pattern.match(password):
print("Strong password")
else:
print("Weak password") # Strong passwordExample 10: Extract Content from XML Tag
xml_data = 'Some description here.'
pattern = re.compile(r'')
title = pattern.search(xml_data).group(1)
print(title) # Sample TitleThese ten examples illustrate how regex can be leveraged to efficiently parse and validate various data formats encountered during API testing.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.