Using Python Lists, Dictionaries, and Tuples in API Automation Testing
This article explains how Python's mutable list and dictionary types and immutable tuple type can be employed to organize test data, build request payloads, and parse JSON responses when automating API tests, providing clear code examples for each use case.
In Python API automation testing, data structures such as lists, dictionaries, and tuples play a crucial role in organizing test data, request parameters, and response results.
List (List) A list is a mutable ordered sequence that can store any type of element. It is often used to hold multiple test data items for batch execution.
users_list = ['user1', 'user2', 'user3']
request_urls = ['http://api.example.com/user/1', 'http://api.example.com/user/2', 'http://api.example.com/user/3']Dictionary (Dictionary) A dictionary is a mutable container of key‑value pairs, where keys are unique and immutable. It is commonly used to construct request parameters and to parse JSON responses.
request_params = {
'username': 'testuser',
'password': 'securepass',
'email': '[email protected]'
}
response_data = {
'id': 1,
'name': 'John Doe',
'status': 'active'
}Tuple (Tuple) A tuple is an immutable ordered sequence. It is useful for storing fixed configuration values that should not be altered during test execution.
fixed_values = ('admin', 'superuser')
coordinates = (40.7128, -74.0060) # example geographic coordinatesUsing a List to Store Multiple Test Cases The following example shows how to iterate over a list of user IDs, send a request for each, and assert the response.
# Define user ID list
user_ids = [1001, 1002, 1003]
# Iterate over each ID and send request
for user_id in user_ids:
response = requests.get(f"https://api.example.com/users/{user_id}")
# Verify response status
assert response.status_code == 200
# Parse JSON response
user_info = response.json()
# Validate required fields
assert 'name' in user_info and 'email' in user_infoUsing a Dictionary to Build Request Payload When sending a POST request with multiple key‑value pairs, a dictionary can encapsulate the JSON body.
import json
import requests
new_user_data = {
'username': 'testuser',
'email': '[email protected]',
'password': 'SecurePassword123!'
}
headers = {'Content-Type': 'application/json'}
response = requests.post("https://api.example.com/users", headers=headers, data=json.dumps(new_user_data))
assert response.status_code == 201 # check successful creationUsing a Tuple to Store Immutable Data For fixed authentication credentials, a tuple ensures the values cannot be changed accidentally.
# Configure authentication credentials
auth_credentials = ('admin', 'secret_password')
response = requests.get("https://api.example.com/private-data", auth=requests.auth.HTTPBasicAuth(*auth_credentials))
# Continue with assertionsParsing JSON Response into a Dictionary API responses in JSON format are typically converted to Python dictionaries for easy access and verification.
# Example JSON response string
response_json = '{"id": 1, "name": "John Doe", "roles": ["admin", "user"]}'
# Convert to dictionary
data_dict = json.loads(response_json)
# Validate contents
assert data_dict['name'] == 'John Doe'
assert 'admin' in data_dict['roles']These examples demonstrate how lists, dictionaries, and tuples can be flexibly applied in Python API automation testing to manage test data, construct requests, and validate responses.
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.