Six Ways to Parameterize API Test Data in Python
This article presents six practical techniques—hard‑coding, using loops, reading from Excel/CSV, loading YAML/JSON files, leveraging pytest parameterization, and querying databases—to manage and reuse API test parameters in Python, each illustrated with clear code examples.
1. Hard‑code parameters directly in the test script, which is simple but inflexible and hard to maintain.
def test_api_request():
response = requests.get("http://example.com/api?param=value")
assert response.status_code == 2002. Store parameters in a variable or list and iterate over them, suitable for multiple similar requests.
params_list = [{"param": "value1"}, {"param": "value2"}]
for params in params_list:
response = requests.get("http://example.com/api", params=params)
assert response.status_code == 2003. Keep test data in Excel or CSV files and read them with pandas or the csv module, ideal for large or complex datasets.
import pandas as pd
# Read Excel file
dataframe = pd.read_excel("test_data.xlsx")
for index, row in dataframe.iterrows():
response = requests.get(f"http://example.com/api?param={row['param']}")
assert response.status_code == 2004. Use YAML or JSON configuration files to manage test data, which are easy to read, edit, and support nested structures.
import json
with open("test_data.json") as file:
data = json.load(file)
for item in data["params"]:
response = requests.get(f"http://example.com/api?param={item['param']}")
assert response.status_code == 2005. Employ the built‑in parameterization features of testing frameworks such as pytest or unittest.
import pytest
@pytest.mark.parametrize("param", ["value1", "value2"])
def test_api_with_param(param):
response = requests.get(f"http://example.com/api?param={param}")
assert response.status_code == 2006. Query a database directly from the test script to obtain parameters in real time.
import sqlite3
connection = sqlite3.connect("test.db")
cursor = connection.cursor()
cursor.execute("SELECT param FROM test_data")
for row in cursor.fetchall():
response = requests.get(f"http://example.com/api?param={row[0]}")
assert response.status_code == 200Test 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.